Accessing the Ninject Kernel Globally

Fred Chateau picture Fred Chateau · Mar 11, 2013 · Viewed 16.6k times · Source

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 the issue in Ninject, than what I am trying to do.

I would like to know whether it is possible to access the Ninject Standard Kernel globally, from its instance in Global.asax.

Here is the code:

public class MvcApplication : NinjectHttpApplication
{
    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();

        // MVC global registration, routing and filtering code goes here...
    }

    protected override IKernel CreateKernel()
    {
        return Container;
    }

    private static IKernel Container
    {
        get
        {
            IKernel kernel = new StandardKernel();
            kernel.Load(new ServiceModule(), new RepositoryModule());
            return kernel;
        }
    }
}

If I have some classes, for example, facade classes that do not interface with the controllers, where I would like to begin a dependency chain, my understanding is I should use:

_className = kernel.Get<IClassName>();

However, the only way I know of to do this is to create a new instance of the Ninject Standard kernel, but if I understand correctly, is is not a good idea to create a new instance of the Ninject kernel, because that is basically creating a second kernel.

So, is it possible to access the existing Kernel that was instantiated in Global.asax at Application Start, from anywhere in my application, or is there a better way entirely to do this?

Regards,

Fred Chateau

Answer

Vasilij picture Vasilij · Oct 25, 2013

The most simple way (IMO):

_className = (IClassName)System.Web.Mvc.DependencyResolver.Current.GetService(typeof(IClassName));