- Dependency Injection and Lifetime Management with ASP.NET Web Api
- Dependency Injection in ASP.NET Web Api with Castle Windsor
In his posts, Mike shows how to use the IHttpControllerActivator to wire up Dependency Injection (DI) without using the built in IDependencyResolver in the Web Api bite. After reading through both of these, I was inspired to create the Ninject based equivalent DI leveraging the IHttpControllerActivator.
Here is the class that I created for this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net.Http; | |
using System.Web.Http.Controllers; | |
using System.Web.Http.Dispatcher; | |
using Ninject; | |
namespace WebApiNinjectIHttpControllerActivator | |
{ | |
public class NinjectKernelActivator: IHttpControllerActivator | |
{ | |
private readonly IKernel _kernel; | |
public NinjectKernelActivator(IKernel kernel) | |
{ | |
_kernel = kernel; | |
} | |
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) | |
{ | |
var controller = (IHttpController) _kernel.Get(controllerType); | |
request.RegisterForDispose( new Release(()=> _kernel.Release(controller))); | |
return controller; | |
} | |
} | |
internal class Release : IDisposable | |
{ | |
private readonly Action _release; | |
public Release(Action release) | |
{ | |
_release = release; | |
} | |
public void Dispose() | |
{ | |
_release(); | |
} | |
} | |
} |
A complete sample application is available from https://github.com/paigecook/WebApiNinjectIHttpControllerActivator