我正在使用像这样的ninject注入httpcontext
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)); }
在Application_start方法中调用RegisterDependencyResolver().
此接口注入到处理会话的类的构造函数中.
任何像context.session [“something”] =“something”的代码都会引发空引用异常.
Application_Start在生命周期中是否过早?我以为.InRequestScope()修复了这个问题,但它对我不起作用.
解决方法
如果您在IIS集成模式下运行,则无法访问Application_Start中的任何Http上下文对象.
试试这样:
private void RegisterDependencyResolver() { kernel .Bind<ISession>() .To<SessionService>() .InRequestScope() .WithConstructorArgument( "context",ninjectContext => new HttpContextWrapper(HttpContext.Current) ); DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel)); }