【问题标题】:Autofac - share instance in scope and child scopesAutofac - 在范围和子范围内共享实例
【发布时间】:2021-02-17 08:32:48
【问题描述】:

我有一个 ASP.NET Core 2.2 应用程序,我想将服务配置为“单例”请求。只要您不创建子范围,就可以使用 InstancePerLifetimeScope。有一些进程在子作用域中运行,是从请求的作用域创建的。

在 ASP.NET Core 2.2 中使用 InstancePerRequest 不起作用(这基本上是我需要的)。

有没有人遇到过这种情况并找到了解决办法?

using(var scope1 = container.BeginLifetimeScope())
{
    var w1 = scope1.Resolve<Worker>(); // should resolve worker 1
    using(scope2 = scope1.BeginLifetimeScope())
    {
        var w2 = scope2.Resolve<Worker>(); // should resolve same worker as w1  
    }
}

using(scope3 = container.BeginLifetimeScope())
{
    var w3 = scope3.Resolve<Worker>();  // should resolve another worker
}

【问题讨论】:

    标签: asp.net-core autofac asp.net-core-2.2


    【解决方案1】:

    看起来您可能希望将Worker 定义为InstancePerMatchingLifetimeScope,然后使用与注册Worker 相同的ID 标记您的外部范围。

    查看标记范围的文档:https://autofaccn.readthedocs.io/en/latest/lifetime/working-with-scopes.html#tagging-a-lifetime-scope

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多