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

转载于:https://www.cnblogs.com/dongshuangjie/p/5312043.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值