ninject/Ninject.Web.Mvc

How may I inject something in the Global.asax ?

vtortola opened this issue · 1 comments

I'm starting a web application with MVC3 and Ninject. There is one dependency that I also need in the Global.asax file that needs to be a singleton.

I thought it should be like this:

public class MvcApplication : NinjectHttpApplication
{
IUserAuthentication _auth;

public MvcApplication()
{
    base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
}

protected override IKernel CreateKernel()
{
    var _kernel = new StandardKernel(new SecurityModule());
    _auth = _kernel.Get<IUserAuthentication>();

    return _kernel;
}

void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
    _auth.ToString();
}

But then I saw that _auth is null when MvcApplication_AuthenticateRequest is called.

Then I tried like this:

public class MvcApplication : NinjectHttpApplication
{
ItUserAuthentication _auth;
IKernel _kernel;

public MvcApplication()
{
    _kernel = new StandardKernel(new SecurityModule());
    _auth = _kernel.Get<IUserAuthentication>();
    base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
}

protected override IKernel CreateKernel()
{
    return _kernel;
}

void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
    _auth.ToString();
}

But now I can see that the constructor is being called several times, therefore I will have several IKernel, and I guess that singleton instances won't be so singleton in my app scope.

How should I do it? Using a static variable?

I put this question also in http://stackoverflow.com/questions/5512040/ninject-ing-a-dependency-in-global-asax

implemented in 4284ad2