MVC 使用IOC实现

实现步骤:

1. 实现IDependencyResolver接口并通过DependencyResolver.SetResolver告知MVC,将部分类型实例解析工作交由IoC容器来处理;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Microsoft.Practices.Unity;



namespace MvcIocDemo.IoC

{

    public class UnityDependencyResolver : IDependencyResolver

    {

        IUnityContainer container;



        public UnityDependencyResolver(IUnityContainer container)

        {

            this.container = container;

        }



        public object GetService(Type serviceType)

        {

            if (!this.container.IsRegistered(serviceType))

            {

                return null;

            }

            return container.Resolve(serviceType);

        }



        public IEnumerable<object> GetServices(Type serviceType)

        {

            return container.ResolveAll(serviceType);

        }

    }

}

2. 继承DefaultControllerFactory,重载GetControllerInstance方法,并通过IoC容器将之注册为IControllerFactory的实现。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

using Microsoft.Practices.Unity;

using System.Web.SessionState;



namespace MvcIocDemo.IoC

{

    public class UnityControllerFactory : DefaultControllerFactory

    {

        IUnityContainer container;

        public UnityControllerFactory(IUnityContainer container)

        {

            this.container = container;

        }



        protected override IController GetControllerInstance(RequestContext reqContext,

            Type controllerType)

        {

            return container.Resolve(controllerType) as IController;

        }



    }



}

3  在函数Application_Start() 中添加如下代码:

        protected void Application_Start()

        {

            AreaRegistration.RegisterAllAreas();



            RegisterGlobalFilters(GlobalFilters.Filters);

            RegisterRoutes(RouteTable.Routes);



            IUnityContainer container = new UnityContainer();

            container.RegisterType<IServiceA, ServiceA>();

            container.RegisterType<IServiceB, ServiceB>();;

            container.RegisterType<IControllerFactory, UnityControllerFactory>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        }

4 在控制器中使用

    public class HomeController : Controller

    {

        protected IServiceA _serviceA;

        protected IServiceB _serviceB;



        public HomeController(IServiceA serviceA, IServiceB serviceB)

        {

            _serviceA = serviceA;

            _serviceB = serviceB;

        }



        public ActionResult Index()

        {

            ViewBag.A = _serviceA.Say();

            ViewBag.B = _serviceB.Write();

            return View();

        }



    }

 

你可能感兴趣的:(mvc)