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