Tuesday, 16 December 2014

Dependency Injection with Unity


Install Microsoft.Practices.Unity.dll using package manager.

Install-Package Unity -Version 3.5.1404

Create an Interface :

    Public interface ITestInterface
    {
        void Insert(string Name);
        string GetName(string PassedName);
    }

Create class :

    Public class clsTestDI : ITestInterface
    {
        public void Insert(string Name)
        {
           
        }

        public string GetName(string PassedName)
        {
            return "Hello " + PassedName;
        }
    }

Create Dependancy Injection  registrattion  & resolver class :

    using Microsoft.Practices.Unity
    using System.Web.Mvc;

    public class DIResolver
    {
        public void Initialise()
        {           
            var container = new UnityContainer();

            // Register Dependancy
            RegisterTypes(container);

            // Resolve Dependancy
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));           
        }
       
        private void RegisterTypes(UnityContainer container)
        {
            // Register Dependancy
            container.RegisterType<ITestInterface, clsTestDI>();
        }
    }

    public class UnityDependencyResolver : IDependencyResolver
    {
        readonly IUnityContainer _container;
        public UnityDependencyResolver(IUnityContainer container)
        {
            this._container = container;
        }

        public object GetService(Type serviceType)
        {
            try
            {               
                return _container.Resolve(serviceType);
            }
            catch
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return _container.ResolveAll(serviceType);
            }
            catch
            {
                return new List<object>();
            }
        }
    }


Register dependency on App_Start event in Global.asax.

        protected void Application_Start()
        {          
            new DIResolver().Initialise();
        }


Now you are able to get access of class’ methods without creating instance (e.g. new class () ;)

  public class ProfileController : Controller
    {
        ITestInterface _Itest;
        public ProfileController(ITestInterface ITest)
        {
            _Itest = ITest;
        }
        //
        // GET: /Profile/
        public new ActionResult Profile()
        {
            string str = _Itest.GetName("Ajay");
            return View();
        }

}