微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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));
}

原文地址:https://www.jb51.cc/csharp/244062.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐