MVC项目用Windsor注入
第一步创建controler 注入类
public class ApiControllersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly().BasedOn<IController>().LifestyleTransient());
}
}
第二步创建windsor安装类
public static class WindsorBootstrapper
{
private static IWindsorContainer _container;
public static void Initialize()
{
_container = new WindsorContainer();
_container.Install(
FromAssembly.This(),
FromAssembly.Containing<RepositoriesInstaller>(),
FromAssembly.Containing<ServicesInstaller>());
_container.Register(Component.For<IWindsorContainer>().Instance(_container).LifestyleSingleton());
var controllerFactory = new WindsorControllerFactory(_container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
public static IWindsorContainer Container()
{
return _container;
}
}
第三步创建 WindsorControllerFactory 工厂类
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel _kernel;
public WindsorControllerFactory(IKernel kernel)
{
_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);
}
}
第四步 在 Global.asax 中调用windsor安装类
protected void Application_Start()
{
WindsorBootstrapper.Initialize();
}