Friday 19 April 2019

Dependency Injection in ASP.Net MVC5 using Unity Ioc Container.

What is Inversion of Control?

Inversion of Control (IoC) refers to a programming style where a framework controls the program flow with the help of Dependency Injection.

The term Inversion of Control (IoC) refers to a programming style where the flow of a program has been inverted i.e. changed from the normal way. As you have done in the example of Class A and Class B. Here, dependencies are instantiated by a framework or runtime and supplied to the desired class as needed.


Step 1: Create a new ASP.NET MVC Application


Step 2: Install Unity Container


Right click on the project and click on Manage NuGet Packages and search for Unity.mvc5. Click to install Unity. mvc5 package in ASP.NET MVC application.






Note
Make sure you are connected with internet.

When it will be installed successfully, you will find the following two references add to your project and UnityConfig.cs file in App_Start Folder at a project level, as shown below:


Step 3: Register all your components with the container as in the following screenshot;


public static class UnityConfig
    {
        public static void RegisterComponents()
        {
var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();

            container.RegisterType<IRepositry, Repositry>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }


Step 4: Add a new Folder in the project of the name Repository and add the following interface and a class in this folder:

//IRepositry.cs
public interface IRepositry
    {
        string GetName();
    }

//Repositry.cs
public class Repositry: IRepositry
    {
        public string GetName()
        {
            return "Vikash Sah";
        }
    }

Step 5: After this register UnityConfig in Global.asax,



Step 6: Finally, use it in your MVC Controller,






No comments:

Post a Comment

Sitecore Publishing Service 7.0 Installation Guide

  About the Publishing Service module The Publishing Service module is an optional replacement for the existing Sitecore publishing methods....