Unity 2.0: Combining InjectionFactory and Automatic Factory

05/06/10

Unity 2.0: Combining InjectionFactory and Automatic Factory

Unity 2.0 is out, and has some very nice features. Two of the coolest are InjectionFactory and Automatic Factories. Nice code samples and tutorials exist, but here’s an example of combining the two features.

using System;
using Microsoft.Practices.Unity;

namespace Unity2Example
{
  class Program
  {
    static void Main()
    {
      using (var container = new UnityContainer())
      {
        container
          .RegisterType<IService, ConcreteService>(
            new InjectionFactory(c => ServiceFactory()));

        Model model = container.Resolve<Model>();

        Console.WriteLine("\nCalling Execute...");
        model.Execute();
        Console.WriteLine("\nCalling Execute...");
        model.Execute();
      }
    }

    static IService ServiceFactory()
    {
      Console.WriteLine("ServiceFactory called.");
      return new ConcreteService();
    }
  }

  interface IService
  {
    void MakeTheCall();
  }

  class ConcreteService : IService
  {
    public ConcreteService()
    {
      Console.WriteLine("ConcreteService instantiated.");
    }

    public void MakeTheCall()
    {
      Console.WriteLine(
        "ConcreteService makes the call.");
    }
  }

  class Model
  {
    public Model(Func<IService> serviceFinder)
    {
      Console.WriteLine("Model instantiated.");

      _serviceFinder = serviceFinder;
    }

    public void Execute()
    {
      _serviceFinder().MakeTheCall();
    }

    private readonly Func<IService> _serviceFinder;
  }
}

This will display:

Model instantiated.

Calling Execute...
ServiceFactory called.
ConcreteService instantiated.
ConcreteService makes the call.

Calling Execute...
ServiceFactory called.
ConcreteService instantiated.
ConcreteService makes the call.

Essentially we’re injecting a Service Locator into our model. My use case for this was injecting an object where the object reference could change (it needed to be deserialized at certain times). This way the dependent class would always get the most current version. It turned out I already had a class that could act as a Service Locator with the addition of an interface, so I injected that instead (it seemed simpler). I think this combination may come in useful someday, though.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.