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();
        }

}

1 comment:

  1. Find a casino that is safe and secure for every gambler
    Read our casino reviews, see if they're good for 평택 출장안마 you and how to 양주 출장샵 find them and 청주 출장안마 if 동두천 출장마사지 they have a very good bonus. Discover slots and casinos 평택 출장샵 with

    ReplyDelete