c# – 使用Ninject,Httpcontext.Session始终为null
发布时间:2020-12-15 08:34:22 所属栏目:百科 来源:网络整理
导读:我正在使用像这样的ninject注入httpcontext private void RegisterDependencyResolver(){ HttpContextBase context = new HttpContextWrapper(HttpContext.Current); var kernel = new StandardKernel(); kernel.BindISession().ToSessionService() .InReque
我正在使用像这样的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)); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |