使用依赖注入时,HttpContext会话为空

使用OWIN和AutoFac作为IoC容器,我试图使用依赖注入将HttpContext注入到会话状态存储机制中,但HttpContext.Session为null。 另外,我不确定它是否重要,但是我试图将HttpContextWrapper(HttpContext.Current)注入到的类是作为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为null。 这里是我的调试器中的观察窗口的图像。 HttpContext.Session为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();
链接地址: http://www.djcxy.com/p/65671.html

上一篇: HttpContext Session is null when using Dependency Injection

下一篇: Autofac Factories with Named Bindings