Httpcontext.Session is always null with Ninject

I embed 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 introduced into the constructor of the class that processes the session.

The problem is that the session is never initialized, so I cannot add anything to it.

Any code, such as context.session ["something"] = "something", raises a link exception.

Is Application_Start Too Early on the Life Cycle? I thought: InRequestScope () fixes this, but it does not work for me.

+6
source share
1 answer

If you are working in integrated IIS mode, you do not have access to any Http context object in Application_Start .

Try it like this:

 private void RegisterDependencyResolver() { kernel .Bind<ISession>() .To<SessionService>() .InRequestScope() .WithConstructorArgument( "context", ninjectContext => new HttpContextWrapper(HttpContext.Current) ); DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel)); } 
+9
source

Source: https://habr.com/ru/post/902959/


All Articles