User Id :    Password :      New Member   Forgot Password  
 
Inversion of Control and Dependency Injection using Unity
Description Inversion of Control (IOC) and Dependency Injection by using Unity   No. of Views     1756
  Rating     0
Author Gaurav   Posted On     18 Sep 2015
Tags .NET Frameworks,ASP.NET 4.0,ASP.NET 4.5    

Sample Code   Download Code

Inversion of Control (IOC) and Dependency Injection:

The main task of IOC and DI is to remove load from the main class and just make the code more maintainable as well as decoupled.
 
Inversion of Control (IOC): IOC is a generic term, it’s a concept where the flow of application is inverted. It can be implemented in several ways like events, delegates and DI.

 
 

 
 
Dependency Injection (DI): Dependency is just a technique which helps to inject dependent object of a class, it just decoupled construction of one class from the construction of the other class.
 
e.g. If you want to make a house building robot & if you want to insert one door , will you go to make a door always by using the row materials or will use the door from the supplier and installed that. I hope to take the door from the supplier and install in the house is the better option. It’s the same thing which dependency injection does.
 
Suppose if an X has a dependency on Y then without the container it is the responsibility of the client to create and inject the instance of class Y.
 
There are few popular .NET dependency injection containers such as:
 
Castle Windsor
StructureMap
Autofac
Unity
Ninject
 
In the following example we will be using Unity to manage the dependencies. It has a simple API and is also easy to configure.
 
We have the following Student class which takes IDataAccess as a constructor dependency. To create loosely coupled architecture using dependency injection we use an interface
which removes the direct dependencies between the classes. So we use IDataAccess parameter in the Student class constructor
 
class Student
        {
            public string Name { get; set; }
            IDataAccess _DataAccess;
            public Student(IDataAccess DataAccess)
            {
                _DataAccess = DataAccess;
            }
        }
 
Adding Unity in our application: To add Unity in your application just right click on the References and click on Manage NuGet Packages as following images:
 

 
 
Just search Unity in the search box and click on Install as shown in the following image:
 
 
 
 
Result of installing the Unity in your project adds the below mentioned references in your project:


 
 
Following references are added to the project
 
Microsoft.Practices.Unity and Microsoft.Practices.Unity.RegistrationByConvention   Main assemblies which implements Dependency Injection functionality
 
Microsoft.Practices.Unity.Configuration We can register the dependencies in an xml file and also in the code. This assembly is useful when we register the dependencies in xml file.
 
Dependency Injection by using Unity Container:

Objects used in application needs to be register in container and retrieve the objects from the container, so it is the container with which our client directly interacts.
 
There are two main steps to use Unity DI container in our application.
 
Register the dependencies:  We register dependencies using the RegisterType method. It is a generic method in which we have the mapping between the interface type or the abstract class and the concrete type which needs to be instantiated when an object of the interface type is requested by the client. First we instantiate the container. Once we have the container object we use the ResgisterType method to add the mapping between the interface and the Concrete types. 
 
 
var container = new UnityContainer();
container.RegisterType<IDataAccess, OracleDataBase>();
 
The above dependency adds a mapping between the IDataAccess and OracleDataBase types. This means that whenever a dependency of type IDataAccess is required an instance of OracleDataBase is created and is injected into the dependent type.
 
Resolve the dependencies:  To create the object which takes a dependency using the constructor or property injection we use the resolve method. When we use the resolve method the necessary dependencies are automatically injected. So there is no need to provide dependencies ourselves. We can get an object of Student class using the Resolve() method as:
 
Student obj = container.Resolve();
 
The Resolve() method will automatically inject the required dependencies in the Student class. Since the Student class depends on the IDataAccess interface and we have registered the mapping between the IDataAccess interface and the OracleDataBase class, an object of OracleDataBase is automatically created by the container and is passed to the Student class constructor.
 
public class Student
    {
        public string Name { get; set; }
        IDataAccess _DataAccess;
        public Student(IDataAccess DataAccess)
        {
            _DataAccess = DataAccess;
        }
    }

    public interface IDataAccess
    {
        string connectionString { get; set; }
    }
    public class OracleDataBase : IDataAccess
    {
        public string _connectionString;
        public string connectionString
        {
            get
            {
                return "check connection";
            }
            set
            {
                _connectionString = value;
            }
        }
    }
   class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.RegisterType<IDataAccess, OracleDataBase>();
            Student obj = container.Resolve<Student>();
        }
    }
 
 
It is very important to register all the dependencies at one place in application. We should register the object to the Unity container at the startup events of the application so that all the object can be available in complete application. In the case of web applications registering the types in the container in the global.asax while for console applications we can register the dependencies in the Main() method and in the WPF application we can register in the app.xaml.cs file.

 

About Author

About Author I am as simple as c#. Gaurav
No Photo
 
Country India
Company N/A
Home Page N/A

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code