Use Ninject to Property inject a dependency into Application_Start method of Global.asax

1.2k Views Asked by At

I'm currently trying to use Ninject and Ninject.Web to inject a dependency into the Global class (Global.asax) in an ASP.NET WebForms Application. As soon as I try to call any of the functions from the injected class (for example in Application_Start) I end up with a NullReferenceException.

Global.asax:

public class Global : System.Web.HttpApplication
{
    [Inject]
    public IJobScheduler JobScheduler { private get; set; }

    protected void Application_Start(object sender, EventArgs e)
    {
        JobScheduler.RegisterOnStartup();
    }
}

NinjectWebCommon.cs

public static class NinjectWebCommon 
{
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<IJobScheduler>().To<JobScheduler>();
    }        
}

IJobScheduler

public interface IJobScheduler
{
    void RegisterOnStartup();
}

JobScheduler

public class JobScheduler : IJobScheduler
{
    public void RegisterOnStartup()
    {
        //Stuff goes in here ...
    }
}

I'm already trying to use the Property Injection, as Constructor Injection isn't possible for the Global class. DI is working everywhere else, just not in my Global.asax where I need to register some stuff during the start up.

I found some answers to related questions like: How do you resolve a Ninject dependency in the global file in ASP.NET? but unfortunately this isn't working for me.

I'm using the following Ninject NuGet packages:

<package id="Ninject" version="3.2.2.0" targetFramework="net40" />
<package id="Ninject.Web" version="3.2.1.0" targetFramework="net40" />
<package id="Ninject.Web.Common" version="3.2.0.0" targetFramework="net40" />
<package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net40" />

Any ideas?

1

There are 1 best solutions below

0
PeterFearn On

I believe the Application_Start method is called before the properties are injected.

See here for more info https://github.com/ninject/ninject.extensions.logging/issues/14