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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/csharp/244062.html

猜你在找的C#相关文章