简体   繁体   English

使用Unity DI创建嵌套的生存期作用域

[英]Created nested lifetime scope with Unity DI

I have a Web API project that uses Unity as the GlobalConfiguration.Configuration.DependencyResolver . 我有一个Web API项目,该项目使用Unity作为GlobalConfiguration.Configuration.DependencyResolver The project uses the Unit of work pattern with a single data access layer that is kept in-memory throughout the lifetime of each request. 该项目使用具有单个数据访问层的工作单元模式,该数据访问层在每个请求的整个生命周期内都保持在内存中。 At the end of each request events are fired, I want to execute the events using their own unique data access layer so that they can be run in parallel (sharing causes concurrency issues). 在每个请求结束时触发事件,我想使用它们自己的唯一数据访问层执行事件,以便它们可以并行运行(共享会导致并发问题)。

How can I create a child lifetime scope within a Http request context? 如何在Http请求上下文中创建子生存期作用域?

I have access to a static instance of UnityDependencyResolver which has the method IDependencyScope BeginScope() , but given it implements System.Web.Http.Dependencies.IDependencyResolver it seems using that is not the correct option? 我可以访问具有方法IDependencyScope BeginScope()UnityDependencyResolver静态实例,但是鉴于它实现了System.Web.Http.Dependencies.IDependencyResolver ,似乎使用的是不正确的选项?

With other DI frameworks such as Autofac, it would be: 使用其他DI框架(例如Autofac),它将是:

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

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

I would prefer to move the events to a different process and fire via message queues but it is not possible at this time. 我希望将事件移至其他进程并通过消息队列触发,但目前尚无法实现。

Unity container can create child container : Unity容器可以创建子容器

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

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

Combine it with different lifetime managers ( HierarchicalLifetimeManager for example) and you can your result. 将其与不同的生命周期管理器 (例如HierarchicalLifetimeManager )结合使用,即可获得结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM