代码改变世界
[登录 · 注册]
  • Castle Windsor 使MVC Controller能够使用依赖注入
  • 以在MVC中使用Castle Windsor为例

    1.第一步要想使我们的Controller能够使用依赖注入容器,先定义个WindsorControllerFactory类,

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Castle.MicroKernel;
    
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;
    
        public WindsorControllerFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }
    
        public override void ReleaseController(IController controller)
        {
            kernel.ReleaseComponent(controller);
        }
    
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }
            return (IController)kernel.Resolve(controllerType);
        }
    }
    

    2.在程序启动的时候添加如下代码

    container = new WindsorContainer().Install(FromAssembly.This());
    var controllerFactory = new WindsorControllerFactory(container.Kernel);
    ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    

    前两步工作我理解为,把生成Controller实例的工作转交给了依赖注入容器的ControllerFactory以替代默认的ControllerFactory

    3.将Controller注入到容器中,我们以Installer的方式注入

    public class ControllersInstaller : IWindsorInstaller
    {
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
    	container.Register(Classes.FromThisAssembly()
    		                   .BasedOn<IController>()
    		                   .LifestyleTransient());
    }
    }
    

    4.在程序启动的时候将Installer添加到容器中

    new WindsorContainer().Install(new ControllersInstaller();
    

    后两步是将所有实现了IController接口的类注册到容器中

  • 上一篇:解决phpmyadmin出现: Maximum execution time of 300
    下一篇:ASP.NET Boilerplate Castle容器无缝添加日志功能
  • 【推广】 阿里云小站-上云优惠聚集地(新老客户同享)更有每天限时秒杀!
    【推广】 云服务器低至0.95折 1核2G ECS云服务器8.1元/月
    【推广】 阿里云老用户升级四重礼遇享6.5折限时折扣!
  • 原文:https://www.cnblogs.com/dongshuangjie/p/5312043.html
走看看 - 开发者的网上家园