Registering Constructor Parameter With Unity Container

Microsoft's Patterns & Practices group provides useful libraries and guidances as open source. Recently, my group deployed the Composite Application Guidance for WPF (aka Prism) which enables loosely coupled application when we architect a large scale software system using user interfaces and backend device conductivities. I've studied it a little bit and soon noticed that this deploys couple of projects developed by Patterns & Practices like Unity Application Block which is part of Enterprise Library, Object Builder and Composite Application Library (CAL). It also inherits the legacy idea of the User Interface Process Application Block(UIPAB).
I faced couple of challenges while using it since it's hard to find any documentation and we need to know every library to utilize Prism a hundred percent.
Among all, one of biggest challenge I've faced was passing constructor parameter when I register a class to the unity container.
First of all, we can get unity container by constructor injection.

public class A
{
  B _b
  public A(B b) { _b = b; }
}

So, if we do

IUnityContainer container = new UnityContainer();
...
A a = container.Resolve<A>();

then the unity container automatically instantiate the parameter b as the type of B and pass it to the constructor. When we had interface type instead of concrete class as parameter and the interface is registered with a concrete class somewhere else, we can expect the registered class will be instantiated as parameter.

public class A
{
  InterfaceToB _b
  public A(InterfaceToB b) { _b = b; }
}

...
IUnityContainer container = new UnityContainer();
container.RegisterType<InterfaceToB, B>();
container.Registertype<InterfaceToA, A>();
...
InterfaceToA a = container.Resolve<InterfaceToA>();

Sometimes, we also want to pass a specific instance as a parameter to this constructor. How to do that?
I've searched internet and msdn for couple of days and just found a mention in the Unity Application Block reference about this.

This goal can be obtained as following.

...
IUnityContainer container = new UnityContainer();
container.RegisterType<InterfaceToB, B>();
container.Registertype<InterfaceToA, A>();
B b = new B();
container.Configure<InjectedMembers>()
            .ConfigureInjectionFor<PatientInfoView>(new InjectionConstructor(b));
...
InterfaceToA a = container.Resolve<InterfaceToA>();

In this way, we can still keep the codes decoupled enough and pass parameters to constructor as we want.

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License