【问题标题】:How to control the scope of Dependency Injection in .Net Core 2如何在 .Net Core 2 中控制依赖注入的范围
【发布时间】:2018-10-16 15:00:28
【问题描述】:

我们正在.Net 2.0 Core 中开发一个类库。我们直接使用依赖注入。我们有一些服务要从容器中解析为“Scoped”。

我们如何在代码中开始(和结束)这样的 Scope。如果能够在我们的一些更复杂的测试场景中做到这一点,那就太好了。

注意:我们不使用“ASP.Net Core”

【问题讨论】:

    标签: c# dependency-injection .net-core


    【解决方案1】:
    using Microsoft.Extensions.DependencyInjection; // it's an extension method
    
    
    
    using (var scope = serviceProvider.CreateScope())
    {
       // in your new Scope, use the scope's ServiceProvider
       var service = scope.ServiceProvider.GetService<SomeService>();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2021-02-02
      相关资源
      最近更新 更多