-
Notifications
You must be signed in to change notification settings - Fork 6
WebAPI Dependency Injection
UCDArch uses Castle Windsor for dependency injection and automatically configures DI for ASPNET MVC Controllers. When using WebAPI controllers within a UCDArch MVC application, you'll have to do a just little extra configuration to hook up DI. Here are the steps:
##1. Register your WebAPI controllers with Castle Windsor
In the UCDArchBootstrapper.cs file, add the following line right below the container.RegisterControllers()
call:
container.Register(Classes.FromThisAssembly().BasedOn<ApiController>().LifestyleTransient());
This simply finds all ApiController classes in the main assembly and registers them with a transient lifestyle (since we need to recreate controller classes on every run).
##2. Create a new IHttpControllerActivator
We'll create a new implementation of IHttpControllerActivator and use it to create the actual WebAPI controller instances. Make a new file called WindsorCompositionRoot.cs and paste in the following code from Mark Seemann's excellent blog post.
public class WindsorCompositionRoot : IHttpControllerActivator
{
private readonly IWindsorContainer _container;
public WindsorCompositionRoot(IWindsorContainer container)
{
this._container = container;
}
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
var controller =
(IHttpController)this._container.Resolve(controllerType);
request.RegisterForDispose(
new Release(
() => this._container.Release(controller)));
return controller;
}
private class Release : IDisposable
{
private readonly Action _release;
public Release(Action release)
{
this._release = release;
}
public void Dispose()
{
this._release();
}
}
}
##3. Hook in this new HttpControllerActivator
Now all that's left is replacing the default HttpControllerActivator with the one created above. In the UCDArchBootstrapper.cs file, paste the following line directly after you initialize the service locator container with IWindsorContainer container = InitializeServiceLocator();
:
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorCompositionRoot(container));
You should be all set, and now when a new WebAPI controller is needed your new HttpControllerActivator will be used with all registered ApiController instances and DI should happen just as you are used to with MVC controllers.