使用依赖注入时,HttpContext Session为null

时间:2017-03-27 18:56:09

标签: c# asp.net session autofac 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 is null

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

1 个答案:

答案 0 :(得分:0)

你能让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();