博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Castle Windsor 使MVC Controller能够使用依赖注入
阅读量:6885 次
发布时间:2019-06-27

本文共 1676 字,大约阅读时间需要 5 分钟。

以在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
() .LifestyleTransient());}}

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

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

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

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

你可能感兴趣的文章
PS2 连接SMB(网线连电脑)和连接USB小记
查看>>
通过Web Deploy方式部署WCF
查看>>
使用xfire工具搭建webservice
查看>>
字符串与数字拼接转换
查看>>
FFMPEG 音频转换命令
查看>>
TestCase--搜索&查询模块
查看>>
Laravle Introduction
查看>>
js便签笔记(13)——jsonp其实很简单【ajax跨域请求】
查看>>
JMeter学习(一)工具简单介绍
查看>>
leetcode/2017-1-1
查看>>
正则表达式 分组
查看>>
python 文件中字符串过滤,并将结果输出到另一个文件中(源码)
查看>>
E:in-range伪类选择器与E:out-of-range伪类选择器
查看>>
签名--数字证书原理
查看>>
二逼平衡树 Tyvj 1730 BZOJ3196 Loj#106
查看>>
值传递和引用传递
查看>>
(RHEL)Linux下的oracle(11g R2)安装过程
查看>>
高性能JavaScript 编程实践
查看>>
powerdesigner 遇到的各种问题总结
查看>>
(转)韦东山linux学习笔记——ubuntu 9.10 软件源问题
查看>>