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.

Get the source code for the factory generation here (project TecX.Unity folder Factories and the test suite that shows how to use it in TecX.Unity.Factories.Test).


2 Responses to Auto-generated Factories with Unity

  1. Pingback: Generate strongly typed factory delegates « Outlawtrail – .NET Development

  2. Pingback: TypedFactory reloaded | Outlawtrail - .NET Development

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: