Friday, October 2, 2009

Unity constructor parameters

I use Microsoft Unity in a project to create several objects. Most of the classes have constructor parameters. Unity uses the most detailed constructor signature (the constructor with the most number of parameters, greedy) to create the object. It’s common you don’t have all the objects registered, so you want to specify some constructor parameters. There are two ways to resolve the object with the proper parameters:

  • You can put an [InjectionConstructor] attribute on the constructor to mark the default constructor.
  • You can create a child container and register the types there.

An example of a child container:

IUnityContainer childCtr = parentCtr.CreateChildContainer();

The child container contains all the registered objects of the parent container. You can freely modify the child container, the parent won’t change. So you can register multiple objects into the child container; they will be the parameters. Finally resolve the desired class using the child container. Unity will automatically inject the previously registered types into the constructor parameters. They will work like local variables.

One huge problem with child container method: you can’t specify different objects for different parameters with the same type. You can resolve one object for one type.