gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:35:35 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com