Jules
Jules

Reputation: 1081

Httpcontext.Session is always null with Ninject

I am injecting the httpcontext using ninject like this

private void RegisterDependencyResolver()
{
    HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
    var kernel = new StandardKernel();
    kernel.Bind<ISession>().To<SessionService>()
                            .InRequestScope()
                           .WithConstructorArgument("context", ninjectContext => context);

    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

RegisterDependencyResolver() is called in the application_start method.

This interface is injected into the constructor of a class that handles session.

The problem is session is never initialised so I cant add anything to it.

Any code like context.session["something"] ="something" raises a null reference exception.

Is Application_Start too early in the lifecycle? I thought .InRequestScope() fixes this but it doesnt work for me.

Upvotes: 6

Views: 2908

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

If you are running in IIS integrated mode you don't have access to any Http context object in Application_Start.

Try like this:

private void RegisterDependencyResolver()
{
    kernel
        .Bind<ISession>()
        .To<SessionService>()
        .InRequestScope()
        .WithConstructorArgument(
            "context", 
            ninjectContext => new HttpContextWrapper(HttpContext.Current)
        );

    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

Upvotes: 9

Related Questions