Dependency Injections
What is Inversion of Control (IOC)?
Inversion of Control (IoC) is a design principle .It is used to invert different kinds of controls in object-oriented design to achieve loose coupled classes. Here, controls refer to any additional responsibilities a class has, other than its main responsibility which may include control over the flow of an application, and control over the flow of an object creation etc.
What is Dependency Injection?
A coding pattern in which a class receives the instances of objects it needs (called dependencies) from a external source rather than creating it self.
Dependency Injection is a software design pattern that implements IoC for resolving dependencies.
Parts of DI (Classes involved)
Client Class: The client class (dependent class) is a class which depends on the service class
Service Class/factory: The service class (dependency) is a class that provides service to the client class.
Injector Class: The injector class injects the service class object into the client class.
Types of Injections
Constructor Injection: here injector supplies the service (dependency) through the client class constructor.
Property Injection: here the injector supplies the dependency through a public property of the client class.
Method Injection: Here we supply the service (dependency) as a parameter to method.
When we have lot of dependencies and dependent following manually doing following tasks are difficult –
- How to identify the dependency?
- How to create instance of dependency?
- How to inject in class constructor?
- So we need to use IOC Container or DI Container
IoC Container or Dependency Injection Container
IoC Container (a.k.a. DI Container) is a framework for implementing automatic dependency injection.It manages object creation of dependency.
It manages it’s life-time, and also injects dependencies to the class.
IoC container uses constructor, a property or method injection.It also disposes it at the appropriate time.
There are many open source or commercial containers available for .NET. Some are –
- Unity
- StructureMap
- Ninject
- Autofac
- DryIoc
- Simple Injector
- Light Inject
Unity DI / Unity Container
Unity container is an open source IoC container for .NET applications supported by Microsoft.
It is a lightweight and extensible IoC container.
It maintains the map of dependency and logic to create the instance of the dependency.
You can install it using Nuget package manager GUI tool or nuget package manager console –
Step 1: Install unity using nuget package manager console –
Install-Package Unity.Mvc5 -Version 1.4.0
When you install the unity, it provides you unity.config file in app_start folder where you need to register the dependencies.
You need to also call the registercomponent method of unity in app_start event go global.asax file.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents(); // <----- Add this line
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Step 2: Register the dependency and dependent in the unity.config file as follows –
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<ICustomer, CustomerRepo>();
container.RegisterType<IEmp, EmpRepo>();
DependencyResolver.SetResolver(new
UnityDependencyResolver(container));
}
Step 3:- Remove the dependency of customer controller from the customer repository and you can modify your code as follows –
ICustomer crepo;
public CustController(ICustomer ctemp)
{
this.crepo = ctemp;
}
public ActionResult Index()
{
return View(this.crepo.GetAll());
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Customer rec)
{
if (ModelState.IsValid)
{
this.crepo.Add(rec);
return RedirectToAction("Index");
}
return View(rec);
}
Step 4: Run the project every thing is perfect.