使用 Unity DI 创建嵌套生命周期作用域

Created nested lifetime scope with Unity DI

我有一个使用 Unity 作为 GlobalConfiguration.Configuration.DependencyResolver 的 Web API 项目。该项目使用具有单个数据访问层的工作单元模式,该数据访问层在每个请求的整个生命周期中都保存在内存中。在每个请求事件结束时触发,我想使用它们自己独特的数据访问层来执行事件,以便它们可以 运行 并行(共享导致并发问题)。

如何在 Http 请求上下文中创建子生命周期范围?

我可以访问具有方法 IDependencyScope BeginScope()UnityDependencyResolver 的静态实例,但考虑到它实现了 System.Web.Http.Dependencies.IDependencyResolver 似乎使用它不是正确的选项?

对于 Autofac 等其他 DI 框架,它将是:

using(var scope = container.BeginLifetimeScope())
{
  var service = scope.Resolve<IService>();

  using(var nestedScope = scope.BeginLifetimeScope())
  {
    var anotherService = nestedScope.Resolve<IOther>();
  }
}

我更愿意将事件移动到不同的进程并通过消息队列触发,但目前不可能。

Unity容器可以create child container:

using(var scope = container.CreateChildContainer())
{
  var service = scope.Resolve<IService>();

  using(var nestedScope = scope.CreateChildContainer())
  {
    var anotherService = nestedScope.Resolve<IOther>();
  }
}

例如将它与 different lifetime managers (HierarchicalLifetimeManager 结合起来)就可以得到你的结果。