Friday, September 5, 2014

Unity Dependency Injection Resolve

Unity Dependency Injection has given us lot of flexibility in terms of customizations and suits to our requirement. There has been good reference and api for Unity MVC , Web API and WCF service. Here is the good free online e-book to start from scratch. It covers everything from DI, AOP, exception handling, caching and customization.

If you looking for creating instance with Unity DI for any class this is what we must do.

Injection constructor
Injection Methods

Few things to keep in mind.
1. We register interface/Class for object reference.
2. We set resolver for each class object
3. We get the resolver.

Option 1
public class MyObject

  public MyObject(SomeClassA objA, SomeClassB objB)

  public MyObject(DependentClassA depA, DependentClassB depB)

IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve();
Option 2

IUnityContainer container= new UnityContainer();
               new InjectionConstructor(
               new ResolvedParameter<DependentClassA>(), new ResolvedParameter<DependentClassB>()));
               var instance= container.Resolve<MyObject>();
We can even have global configuration to resolve all our object instance for any class library.
Post a Comment