Generate strongly typed factory delegates

Unity provides automatic factories (delegates in the form Func<T>) out of the box. TecX adds TypedFactories. And now you can also tell the container to generate strongly typed factory delegates for you. Imagine you have the following definition of a factory delegate:

public delegate IUnitOfWork UnitOfWorkFactory(bool isReadOnly);

And a consumer of the delegate that looks something like this:

public class Consumer
{
  private readonly UnitOfWorkFactory factory;
  public Consumer(UnitOfWorkFactory factory)
  {
    this.factory = factory;
  }
  public UnitOfWorkFactory Factory { get { return this.factory; } }
  // [...]
}

What’s inside the IUnitOfWorkinterface does not matter. Its implementation is more interesting:

public class UnitOfWork : IUnitOfWork
{
  private readonly bool isReadOnly;
  public UnitOfWork(bool isReadOnly)
  {
    this.isReadOnly = isReadOnly;
  }
  public bool IsReadOnly { get { return this.isReadOnly; } }
  // [...]
}

Notice that the name of the parameter the delegate takes equals the name of the constructor parameter of UnitOfWork.

The following test runs green.

var container = new UnityContainer();
container.RegisterType<UnitOfWorkFactory>(new DelegateFactory());
container.RegisterType<IUnitOfWork, UnitOfWork>();
Consumer consumer = container.Resolve();
UnitOfWork uow = consumer.Factory(true) as UnitOfWork;
Assert.IsNotNull(uow);
Assert.IsTrue(uow.IsReadOnly);

That means that Unity generates a UnitOfWorkFactory delegate under the covers and injects it into the constructor of the Consumer class. The DelegateFactory also forwards the parameter you have to provide when calling the delegate.

So that’s yet another way not to write code for a factory.

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

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: