Httpcontext.Session总是带着Ninject空 [英] Httpcontext.Session is always null with Ninject

查看:163
本文介绍了Httpcontext.Session总是带着Ninject空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用注射像ninject这个的HttpContext

I am injecting the httpcontext using ninject like this

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

RegisterDependencyResolver()被调用在Application_Start方法。

RegisterDependencyResolver() is called in the application_start method.

此接口被注入到处理会话类的构造函数。

This interface is injected into the constructor of a class that handles session.

问题是会话初始化从来没有,所以我不能添加任何东西给它。

The problem is session is never initialised so I cant add anything to it.

任何code像context.session [东西] =东西提出了一个空引用异常。

Any code like context.session["something"] ="something" raises a null reference exception.

时的Application_Start在生命周期的太早了?我以为.InRequestScope()修复了这个,但它不为我工作。

Is Application_Start too early in the lifecycle? I thought .InRequestScope() fixes this but it doesnt work for me.

推荐答案

如果您在IIS集成模式下运行,你没有访问任何HTTP上下文对象的Application_Start

If you are running in IIS integrated mode you don't have access to any Http context object in Application_Start.

尝试这样的:

private void RegisterDependencyResolver()
{
    kernel
        .Bind<ISession>()
        .To<SessionService>()
        .InRequestScope()
        .WithConstructorArgument(
            "context", 
            ninjectContext => new HttpContextWrapper(HttpContext.Current)
        );

    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

这篇关于Httpcontext.Session总是带着Ninject空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆