使用依赖注入时 HttpContext Session 为空

HttpContext Session is null when using Dependency Injection

使用 OWIN 和 AutoFac 作为 IoC 容器,我试图使用依赖注入将 HttpContext 注入会话状态存储机制,但 HttpContext.Session 为空。另外,我不确定它是否重要,但我试图将 HttpContextWrapper(HttpContext.Current) 注入的 class 是我作为 nuget 包构建的外部 dll。

Autofac注册,注册我的Autofac模块

 public static void Register(IAppBuilder app)
    {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();
            builder.RegisterFilterProvider();

            builder.RegisterModule(new GatewayModule());

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            app.UseAutofacMiddleware(container);
    }

autofac 模块的代码:

public class GatewayModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<SessionStateTokenStore>()
            .WithParameter(new TypedParameter(typeof(HttpContextBase), new HttpContextWrapper(HttpContext.Current)))
            .As<ITokenStore>().InstancePerRequest();
    }
}

但是,当我查看我的 SessionStateTokenStore 时,_httpContext.Session 为空。这是我的调试器中手表 window 的图像。 HttpContext.Session is null

为什么 HttpContext.Session 为空,我该如何解决?

能否让Autofac解析HttpContextBase,看看是否解决了问题?

// HttpContext
builder.Register(c => new HttpContextWrapper(HttpContext.Current) as HttpContextBase)
   .As<HttpContextBase>().InstancePerLifetimeScope();
builder.Register(c => c.Resolve<HttpContextBase>().Request)
   .As<HttpRequestBase>().InstancePerLifetimeScope();
builder.Register(c => c.Resolve<HttpContextBase>().Response)
   .As<HttpResponseBase>().InstancePerLifetimeScope();
builder.Register(c => c.Resolve<HttpContextBase>().Server)
   .As<HttpServerUtilityBase>().InstancePerLifetimeScope();
builder.Register(c => c.Resolve<HttpContextBase>().Session)
   .As<HttpSessionStateBase>().InstancePerLifetimeScope();

builder.RegisterType<SessionStateTokenStore>()
   .As<ITokenStore>().InstancePerRequest();