簡體   English   中英

使用Ninject時,Httpcontext.Session始終為null

[英]Httpcontext.Session is always null with Ninject

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM