zoukankan      html  css  js  c++  java
  • 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接口的类注册到容器中

  • 相关阅读:
    许昌 地图。满屏的饭馆。
    Python中的math和保留小数位数方法
    Python中的math和保留小数位数方法
    python对XML 操作
    python对XML 操作
    python的enumerate()函数
    python的enumerate()函数
    [COJ0989]WZJ的数据结构(负十一)
    [OpenJudge 3066]随机序列
    [OpenJudge 3064]坠落的蚂蚁
  • 原文地址:https://www.cnblogs.com/dongshuangjie/p/5312043.html
Copyright © 2011-2022 走看看