This question is not specifically related to Ninject. It\'s more of a general coding question, but I\'m posting it here in case there might be a better way entirely of handling
I managed to get the Service Locator working, and it appears to be working quite well. When a request enters the application through an MVC Controller Action Method, Ninject functions in the normal way provided by Ninject.Mvc.Extensions. It injects instance classes through the controller constructor. When a request enters the application in any other way, I call the Service Locator to supply the instance classes in that classes constructor.
Here's the code:
First, a reference to Microsoft.Practices.ServiceLocation
And the following Ninject adapter class.
public class NinjectServiceLocator : ServiceLocatorImplBase
{
public IKernel Kernel { get; private set; }
public NinjectServiceLocator(IKernel kernel)
{
Kernel = kernel;
}
protected override object DoGetInstance(Type serviceType, string key)
{
return Kernel.Get(serviceType, key);
}
protected override IEnumerable
And in Global.asax
public class MvcApplication : NinjectHttpApplication
{
private static IKernel _kernel;
protected override IKernel CreateKernel()
{
return Container;
}
private static IKernel Container
{
get
{
if (_kernel == null)
{
_kernel = new StandardKernel();
_kernel.Load(new ServiceModule(), new RepositoryModule());
ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(_kernel));
}
return _kernel;
}
}
}
Note this code requires the use of Ninject.Mvc.Extensions, which provides dependency resolver fallback to the default controller. Otherwise, a custom dependency resolver may be required.
This appears to resolve all my concerns. It creates the instance classes, resolves the entire object graph, and works from anywhere I need it to work. And, as far as I can tell, there is only one Ninject Standard Kernel per application.
I know using the Service Locator pattern is frowned upon, but I imagine using more than one Ninject kernel would be frowned upon even worse.
Fred Chateau