2017-03-27 71 views
1

使用OWIN和AutoFac作爲IoC容器,我試圖使用依賴注入將HttpContext注入會話狀態存儲機制,但HttpContext.Session爲null。另外,我不確定它是否重要,但是我試圖將HttpContextWrapper(HttpContext.Current)注入到的類是作爲nuget包構建的外部dll。使用依賴注入HttpContext會話爲空

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爲空。這裏是我的調試器中的觀察窗口的圖像。 HttpContext.Session is null

爲什麼HttpContext.Session爲空,我該如何解決它?

回答

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(); 
+0

謝謝!這工作,我曾嘗試過,但是很愚蠢,仍然註冊.WithParameter(新TypedParameter(typeof(HttpContextBase),新HttpContextWrapper(HttpContext.Current)))讓Autofac解析HttpContextBase後。事實證明,你也可以註冊AutofacWebTypesModule,它和你的建議一樣,再加上一些。 – csalzsieder