• 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接口的类注册到容器中

  • 相关阅读:
    WPF 如何画一颗心
    WPF 通过Border来画边框
    WPF 如何引入外部样式
    WPF 变量转换的实现
    WPF 动画显示控件
    wpf 悬浮窗口的实现
    WPF 如何绘制不规则按钮,并且有效点击范围也是不规则的
    WPF 变量绑定实现
    2016年终总结:从程序员到项目经理的转身
    使用FastReport打印二维码
  • 原文地址:https://www.cnblogs.com/dongshuangjie/p/5312043.html
Copyright © 2020-2023  润新知