2014-02-20 52 views
2

我有有很多部件採用InstancePerHttpRequest範圍註冊一個asp.net MVC的網站,但我也有一個「後臺任務」,這將運行,不會有一個HttpContext的每隔幾個小時。配置Autofac容器的後臺線程

我想獲得已註冊這樣

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)) 
    .InstancePerHttpRequest(); 

我IRepository的實例,我如何做到這一點從使用Autofac非HTTP上下文?我認爲IRepository應該使用InstancePerLifetimeScope

+0

見http://stackoverflow.com/a/27903481/389424 – janv8000

回答

5

還有的你如何能做到這幾個方面:

  1. 在我看來,最好的一個。如您所說,您可以將存儲庫註冊爲InstancePerLifetimeScope。它同樣適用於HttpRequests和LifetimeScopes。

    builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)) 
        .InstancePerLifetimeScope(); 
    
  2. 您的HttpRequest的註冊可能從註冊差異,LifetimeScope,那麼你可以有兩個獨立的登記:

    builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)) 
        .WithParameter(...) 
        .InstancePerHttpRequest(); // will be resolved per HttpRequest 
    
    builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)) 
        .InstancePerLifetimeScope(); // will be resolved per LifetimeScope 
    
  3. 可以明確創建使用它的標籤"HttpRequest"範圍。在新版本中通過MatchingScopeLifetimeTags.RequestLifetimeScopeTag屬性公開。

    using (var httpRequestScope = container.BeginLifetimeScope("httpRequest")) // or "AutofacWebRequest" for MVC4/5 integrations 
    { 
        var repository = httpRequestScope.Resolve<IRepository<Entity>>(); 
    } 
    
+0

我沒有選項3這樣的:_container.BeginLifetimeScope( 「AutofacWebRequest」) – Paul

+0

@保羅感謝。要求標籤在新的版本中改爲「AutofacWebRequest」,並暴露於通過MatchingScopeLifetimeTags.RequestLifetimeScopeTag。更新了答案。 –

+0

#1效果很好。爲了讓容器可以做到以下幾點:'VAR容器= AutofacDependencyResolver.Current.ApplicationContainer;' –