Auto-generated Factories with Unity

If you need to create objects after the initialization of your object graph by the container injecting factories is the way to go.

But defining factory interfaces and/or abstract base classes, implementing them and duplicating the knowledge your container already has does not make sense. For these scenarios Castle Windsor has it's Typed Factory Facilities.

Define just the factory interface. Register it with the container and tell the container to generate an implementation for you. After all the implementation does not matter. Its a detail the consumers should not have to care about. If you need to forward runtime parameters like ConnectionStrings or file names the container takes care of that too.

With TecX.Unity.Factories you get the same set of features for Unity as well. All of a sudden using factories becomes as easy as this:

public interface IMyFactory
{
  IFoo Create(string name);
}
public interface IFoo
{
  string Name { get; }
}
public class Foo : IFoo
{
  public string Name { get; set; }
  public Foo(string name)
  {
    this.Name = name;
  }
}
var container = new UnityContainer();
container.RegisterType<IMyFactory>(new TypedFactory());
container.RegisterType<IFoo, Foo>();
var factory = container.Resolve<IMyFactory>();
var foo = factory.Create("some name");
Assert.AreEqual("some name", foo.Name);

This also works for property injection as long as you mark the property for injection by the container.

container.RegisterType<IFoo, Foo>(new InjectionProperty("Name"));

After a major overhaul of its internals the TypedFactory no longer relies on Castle DynamicProxy for the generation of the interface implementation. Unity brings its own powerful block for interception. It just insists that there has to be a target object for the interception pipeline. After integrating the technique used to generate lazy proxies auto-generating factories is now a Unity-only implementation.

Last edited Jul 8, 2012 at 7:15 AM by weberse, version 4

Comments

No comments yet.