Dependency Injection Techniques Explained - Using Unity Container

In the previous article, we discussed how to use StructureMap to inject dependencies at runtime.
 
A brief introduction to Unity Container
 
The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.
 

Implementing the Dependency Injection with Unity Container

 
According to MSDN
 
The Unity Container (Unity) is a lightweight, extensible dependency injection container. It facilitates building loosely coupled applications and provides developers with the following advantages:
  • Simplified object creation, especially for hierarchical object structures and dependencies
  • Abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify
 Management of crosscutting concerns
  • Increased flexibility by deferring component configuration to the container
  • Service location capability; this allows clients to store or cache the container
  • Instance and type interception
You need to add a reference to Microsoft.Practices.Unity to work with Unity container.
 
Note: Here are we are dealing with a simple implementation of Unity Container. You can use Unity Container for maintaining the object's lifetime by specifying that the object will work as a singleton that serves all the requests or per call and many other things. You are advised to go through MSDN for more details.
 
Setter Injector using Unity
 
So, here is my code to implement the Unity Container:
  1. static void Main(string[] args)  
  2. {  
  3.        IClassA classA = new ClassA();//creating instance of class A   
  4.        IUnityContainer unityContainer = new UnityContainer();  
  5.        unityContainer.RegisterType<IClassB, ClassB>();   
  6.        var classB = unityContainer.Resolve<IClassB>();  
  7.    
  8.        //assign the instance to the classB property of class A  
  9.        classA.ClassB = classB;   
  10.   
  11.       //Call the method  
  12.       classA.DoSomethingFromClassB();   
  13.       Console.Read();   
First, we are creating an instance of Unity Container
  1. IUnityContainer unityContainer = new UnityContainer(); 
Then we are registering the interfaces and their concrete classes
  1. unityContainer.RegisterType<IClassB, ClassB>(); 
Now asking the Container to resolve to get the actual instance of the concrete class
  1. var classB = unityContainer.Resolve<IClassB>(); 
But the Unity Container can intelligently identify what dependency object should be created if you specify the attribute [Dependency] in the consuming class setter methods.
 
You can see it in practice as below
 
I am modifying the code to test it.
  1. public class ClassA : IClassA  
  2. {  
  3.     private IClassB _classB;  
  4.     [Dependency]  
  5.     public IClassB ClassB  
  6.     {  
  7.         get { return _classB; }             
  8.         set  
  9.         {  
  10.             if (value == nullthrow new ArgumentNullException("value");  
  11.             _classB = value;  
  12.         }  
  13.     }   
  14.     public void DoSomethingFromClassB()  
  15.     {  
  16.         _classB.DoSomething();  
  17.     }  
Now my Program class looks like the following:
  1. static void Main(string[] args)  
  2. {  
  3.       IUnityContainer unityContainer = new UnityContainer();  
  4.       unityContainer.RegisterType<IClassB, ClassB>();   
  5.       IClassA classA = new ClassA();//creating instance of class A   
  6.       var instance = unityContainer.Resolve<ClassA>();  
  7.            
  8.      //Call the method  
  9.      instance.DoSomethingFromClassB();    
  10.      Console.Read();   
If you observe in the preceding code I specified the attribute [Dependency] above the public property of class A and in the Main method, I have created the instance of Class A and it is asking Unity to resolve all its dependencies so that I do not need to explicitly create the dependent objects.
  1. var instance = unityContainer.Resolve<ClassA>();  
1.png
 

Constructor Injector using Unity

 
To implement this, I have changed my interface as below:
  1. public interface IClassA  
  2. {  
  3.     //IClassB ClassB { get; set; }  
  4.     void DoSomethingFromClassB();  
Now class A looks as in the following:
  1. public class ClassA : IClassA  
  2. {  
  3.     private readonly IClassB _classB;   
  4.     [InjectionConstructor]  
  5.     public ClassA(IClassB classB)  
  6.     {  
  7.         _classB = classB;  
  8.     }   
  9.     public void DoSomethingFromClassB()  
  10.     {  
  11.         _classB.DoSomething();  
  12.     }  
Observe the attribute [InjectionConstructor]. This tells the Unity that the ClassA is dependent on an object which is to be injected in a constructor.
 
Now the Main program looks as in the following
  1. static void Main(string[] args)  
  2. {  
  3.      IUnityContainer unityContainer = new UnityContainer();  
  4.      unityContainer.RegisterType<IClassB, ClassB>();  
  5.      var instance = unityContainer.Resolve<ClassA>();  
  6.      instance.DoSomethingFromClassB();  
  7.      Console.Read();  
Here I am just specifying that we need to create an instance of ClassA by resolving all its dependencies i.e. dependent objects should be resolved by the Unity Container.
var instance = unityContainer.Resolve<ClassA>();
 
Method Injector using Unity Container
 
In this, we are going to inject the dependency using a method in a class. In our example, ClassA has a method that takes IClassB type as a parameter. Using a Unity Container we are going to inject the dependency into the class ClassA. In the classA, we are going to decorate the method with the attribute [InjectionMethod].
  1. public interface IClassA  
  2. {  
  3.     void DoSomethingFromClassB();  
  4.     void SetClassB(IClassB classB);  
  5. }   
  6. public class ClassA : IClassA  
  7. {  
  8.     private  IClassB _classB;   
  9.     [InjectionMethod]  
  10.     public void SetClassB(IClassB classB)  
  11.     {  
  12.         _classB = classB;  
  13.     }   
  14.     public void DoSomethingFromClassB()  
  15.     {  
  16.         _classB.DoSomething();  
  17.     }  
  18. }  
  19. static void Main(string[] args)  
  20. {   
  21.       IUnityContainer unityContainer = new UnityContainer();  
  22.       unityContainer.RegisterType<IClassB, ClassB>();  
  23.       var instance = unityContainer.Resolve<ClassA>();  
  24.       instance.DoSomethingFromClassB();  
  25.       Console.Read();    
In the preceding example, we are registering the classes that Unity is supposed to resolve dynamically by reading the attributes of the class. Here, the unity container without explicitly specifying the details of ClassA reads all the attributes in ClassA and resolves all the dependencies in the ClassA by instantiating the dependent objects and injecting them.
 
In the next article, we will be discussing how to implement it using the Ninject Container.


Similar Articles