为后台线程配置Autofac容器

Pau*_*aul 2 asp.net backgroundworker autofac

我有一个asp.net MVC站点,它有许多使用InstancePerHttpRequest范围注册的组件,但是我还有一个"后台任务",每隔几个小时运行一次,没有httpcontext.

我想得到一个我的IRepository的实例,它已经像这样注册了

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
     .InstancePerHttpRequest();
Run Code Online (Sandbox Code Playgroud)

如何使用Autofac从非http上下文中执行此操作?我认为IRepository应该使用InstancePerLifetimeScope

Ale*_*tin 6

有几种方法可以做到这一点:

  1. 我认为最好的一个.您可以按照说明将存储库注册为InstancePerLifetimeScope.它同样适用于HttpRequests和LifetimeScopes.

    builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
        .InstancePerLifetimeScope();
    
    Run Code Online (Sandbox Code Playgroud)
  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
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您可以"HttpRequest"使用其标记显式创建范围.MatchingScopeLifetimeTags.RequestLifetimeScopeTag在新版本中通过属性公开.

    using (var httpRequestScope = container.BeginLifetimeScope("httpRequest")) // or "AutofacWebRequest" for MVC4/5 integrations
    {
        var repository = httpRequestScope.Resolve<IRepository<Entity>>();
    }
    
    Run Code Online (Sandbox Code Playgroud)