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 IUnitOfWork interface 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<Consumer>();
UnitOfWork uow = consumer.Factory(true) as UnitOfWork;

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.

See the TecX.Unity project (inside the Factories folder) for the source code and TecX.Unity.Test for tests.

Last edited May 16, 2012 at 9:39 AM by weberse, version 1


No comments yet.