2014-02-20 53 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;' –