ASP. NET Web API, asp. netwebapi
Sample Code
When the project is started, create a dependency injection container
Define a static container IWindsorContainer
1 private static IWindsorContainer _ container;
In Application_Start (), create the container
1 _ container = new WindsorContainer ();
Call the Container Install method to register components in the Container.
1 _ container. Install (FromAssembly. This ());
This statement calls all Install methods in the IWindsorInstaller Interface Class in the entire Assembly to register components with the container. Run the following code:
1 public void Install(IWindsorContainer container, IConfigurationStore store)2 {3 container.Register(4 Component.For<IDPlatypusRepository>().ImplementedBy<DPlatypusRepository>().LifestylePerWebRequest());5 }
Specifically list the code for registering a Controler in the Container:
1 public void Install(IWindsorContainer container, IConfigurationStore store)2 {3 container.Register(Classes.FromThisAssembly()4 .BasedOn<ApiController>().LifestylePerWebRequest());5 }
Defines the WindsorDependencyResolver class that implements the IDependencyResolver interface, as the Resolver of global HttpConfiguration
var dependencyResolver = new WindsorDependencyResolver(_container);configuration.DependencyResolver = dependencyResolver;
Create an IHttpControllerActivator and change the Controller creation method to get
Implement the Create method of the IHttpControllerActivator Interface
1 public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)2 {3 var controller = (IHttpController)_container.Resolve(controllerType);4 5 request.RegisterForDispose(6 new Release(() => _container.Release(controller)));7 8 return controller;9 }
And register the Controller when the web request is Dispose.
Replace Default IHttpControllerActivator Behavior
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator),new WindsorCompositionRoot(container));
References:
Simplest Possible ASP. NET Web API Project that Implements IoC/DI using Castle Windsor
Http://www.codeproject.com/Articles/710662/Simplest-Possible-ASP-NET-Web-API-Project-that-Imp
WebAPI Dependency Injection
Https://github.com/ucdavis/UCDArch/wiki/WebAPI-Dependency-Injection
Difference between inheriting ApiController vs. IHttpController
Http://stackoverflow.com/questions/21464909/difference-between-inheriting-apicontroller-vs-ihttpcontroller
ASP. net web api 2: HTTP MESSAGE LIFECYLE
Http://www.asp.net/posters/web-api/asp.net-web-api-poster.pdf
Use Castle Windsor to implement Web API dependency Injection
Http://beginor.github.io/2014/12/21/webapi-dependency-injection-with-castle-windsor.html