Sample code
Create a Dependency injection container when the project starts
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 the component inside the container
1 _container. Install (Fromassembly.this ());
The statement calls the entire assembly that implements the Install method in the Iwindsorinstaller interface class to register the component with the container. such as the following code:
1 Public void Install (IWindsorContainer container, Iconfigurationstore store) 2 {3 container. Register (4 component.for<idplatypusrepository> (). Implementedby<dplatypusrepository>(). Lifestyleperwebrequest ()); 5 }
Specifically, the code that registers controler with Container is listed:
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 a global httpconfiguration Resolver
var New = dependencyresolver;
Create a new Ihttpcontrolleractivator, change the Controller creation method to get from the container Container
Implementing the Ihttpcontrolleractivator Interface Create method
1 PublicIhttpcontroller Create (httprequestmessage request, Httpcontrollerdescriptor Controllerdescriptor, Type Controllertype)2 {3 varController =(Ihttpcontroller) _container. Resolve (controllertype);4 5 request. Registerfordispose (6 NewRelease (() =_container. Release (Controller));7 8 returnController;9}
and registers the Controller when the Web request is dispose of.
Replace Default ihttpcontrolleractivator Behavior
GlobalConfiguration.Configuration.Services.Replace (typeof(ihttpcontrolleractivator),New Windsorcompositionroot (container));
Resources:
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
Implementing Web API Dependency Injection using Castle Windsor
Http://beginor.github.io/2014/12/21/webapi-dependency-injection-with-castle-windsor.html
ASP. NET Web API-using Castle Windsor Dependency Injection