使用Unity在MVC上实现动态注入

时间:2023-03-09 16:32:51
使用Unity在MVC上实现动态注入

一、前言

通过前一篇的文章介绍使用unity轻量级的依赖注入容器,本文就介绍在MVC上使用unity依赖注入控制器和控制器中的日志属性。

实现MVC中新提供 的两个接口:IDependencyResolver和  IControllerActivator

二、代码实现

自定义创建CustomControllerActivator类实现IControllerActivator接口的方法

   public class CustomControllerActivator : IControllerActivator
    {
        IController IControllerActivator.Create( System.Web.Routing.RequestContext requestContext,  Type controllerType)
        {
            return DependencyResolver.Current.GetService(controllerType) as IController;   //从容器中创建的HomeController转换成 IController
        }
    }

还要创建一个UnityDependencyResolver类实现IDependencyResolver接口的GetService和GetServices方法

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

        public object GetService(Type serviceType)
        {
            try
            { //启动HomeController 控制器,就会创建HomeController,//而且HomeController里面有个public ILogger Logger { get; set; }日志属性,上面打了 [Dependency]特性,//并且GetUnityContainer()方法里面也已经给日志属性注册了FlatFileLogger了,所以默认创建HomeController的时候,也给日志属性注入FlatFileLogger
                return container.Resolve(serviceType);
            }
            catch
            {
                return null;
            }
        }

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

定义好这两个类,我们找到Global.asax.cs,并在其中中添加一个私有方法GetUnityContainer()

        private IUnityContainer GetUnityContainer()
        {

            IUnityContainer container = new UnityContainer()
            .RegisterType<IControllerActivator, CustomControllerActivator>()
            .RegisterType<ILogger, FlatFileLogger>();
            return container;
        }

然后在Application_Start方法中添加如下代码,首先通过GetUnityContainer方法获得container,并且设置当前的Resolver是我们自己实现的UnityDependencyResolver。

protected void Application_Start()
        {

            IUnityContainer container = GetUnityContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }

在Controller中我们只需要添加一个[Dependency]特性,就可以很方便的获取到我们注入的Logger。

    public class HomeController : Controller
    {

        [Dependency]
        public ILogger Logger { get; set; }

        public ActionResult Index()
        {

            ViewBag.Message = "我来了!!!";

            Logger.Write("哈哈哈");

            return View();
        }

    }

相关文章