asp.net - 为后台线程配置 Autofac 容器

标签 asp.net backgroundworker autofac

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

我想要一个像这样注册的 IRepository 实例

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

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

最佳答案

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

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

关于asp.net - 为后台线程配置 Autofac 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896002/

相关文章:

c# - 占位符外的母版页内容

multithreading - 为什么 TApplication.MessageBox 自动关闭?

rabbitmq - 用于根据收到的每条消息设置 Multi-Tenancy 范围值的预期 MassTransit 中间件构造是什么?

javascript - Jquery 验证后 OnClick 不起作用

c# - 如何在 SQL Server 2008 上运行定期进程

c# - 如何使用按钮启动和停止持续运行的后台工作程序

c# - 使用 Ninject 的 Autofac InstancePerHttpRequest

asp.net-mvc - 为什么 autofac 在 HttpRequest 结束之前处理对象?

javascript fire C# 点击事件

c# - BackgroundWorker 和线程