web Api 用 windsor 注入
第一步 创建API controller 注入类
public class ApiControllersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly().BasedOn<System.Web.Http.ApiController>().LifestyleTransient());
}
}
第二步 创建windsor contain 安装类
public static class WindsorBootstrapper
{
private static IWindsorContainer _container;
public static void Initialize()
{
_container = new WindsorContainer();
_container.Install(FromAssembly.This());
_container.Register(Component.For<IWindsorContainer>().Instance(_container).LifestyleSingleton());
}
public static IWindsorContainer Container
{
get
{
return _container;
}
}
}
}
第三步 创建WindsorCompositionRoot 类
public class WindsorCompositionRoot:IHttpControllerActivator
{
private readonly IWindsorContainer _container;
public WindsorCompositionRoot(IWindsorContainer container)
{
_container = container;
}
public IHttpController Create( HttpRequestMessage request,HttpControllerDescriptor controllerDescriptor,Type controllerType)
{
var controller =
(IHttpController)_container.Resolve(controllerType);
request.RegisterForDispose(
new Release(
() => _container.Release(controller)));
return controller;
}
private class Release : IDisposable
{
private readonly Action _release;
public Release(Action release)
{
_release = release;
}
public void Dispose()
{
_release();
}
}
}
第四步 Global.asax 注入
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
WindsorBootstrapper.Initialize();
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator),new WindsorCompositionRoot(WindsorBootstrapper.Container));
}
}