Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
Jules Avatar asked Dec 02 '11 19:12

Jules


1 Answers

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));
}
like image 168
Darin Dimitrov Avatar answered Sep 30 '22 00:09

Darin Dimitrov