c# – 使用Ninject,Httpcontext.Session始终为null

我正在使用像这样的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));
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...