I ran into a problem today where I needed to inject dependencies into a handler. Typically, you don’t really have access to the kernel here and I saw this as a problem as my handler had its own dependencies which needed to be resolved.
After much research, it doesn’t appear people use Ninject here…or they don’t document it…anyway, I decided to add a method to get the created kernel from the NinjectWebCommon class called GetKernel. Please note that this snippet also includes the declaration for a NinjectDependencyResolver.
Now I’ve exposed my kernel via this method I can then use it in the WebApiConfig class. This doesn’t seem ideal but there seems to be tons of different ways to configure Ninject dependant on the type of web project you’re creating.
If anyone has any better way to achieve the same results, please let me know in the comments!
Update! I noticed after writing this tutorial, you don't have to add the ExceptionHandler to the services within the WebApiConfig class. It's probably using reflection to check for any classes implementing IExceptionHandler and using that implementation. Needless to say, there might still be instances where having the kernel in the WebApiConfig is neccessary so it's good to note the above method.