HttpContext Session is null when using Dependency Injection

Using OWIN and AutoFac as the IoC container, I am trying to use Dependency Injection to inject HttpContext into a session state storage mechanism, but HttpContext.Session is null. Also, I am not sure if it matters but the class that I am trying to inject HttpContextWrapper(HttpContext.Current) into is an external dll that I have built as a nuget package.

Autofac registration, registers my Autofac module

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

And the code for the autofac module:

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

However, when I look into my SessionStateTokenStore, _httpContext.Session is null. Here is an image of my watch window in my debugger. HttpContext.Session is null

Why is HttpContext.Session null and how do I fix it?


你可以让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/65672.html

上一篇: 通用属性和IoC(Autofac)问题

下一篇: 使用依赖注入时,HttpContext会话为空