如何在 .NET Core 中使用默认依赖注入从父作用域创建子作用域?

How to create a child scope from the parent with default dependency injection in .NET Core?

我正在构建一个控制台 .NET Core 应用程序。它周期性地运行一个做一些工作的方法。如何使 ServiceProvider 的行为方式与 ASP.NET 核心应用程序中的行为方式相同。我希望它在方法开始执行时解析范围内的服务,并在方法结束时处理解析的服务。

// pseudocode

globalProvider.AddScoped<ExampleService>();

// ...

using (var scopedProvider = globalProvider.CreateChildScope())
{
    var exampleService = scopedProvider.Resolve<ExampleService>();
}

使用IServiceProvider.CreateScope()方法创建本地作用域:

var services = new ServiceCollection();
services.AddScoped<ExampleService>();
var globalProvider = services.BuildServiceProvider();

using (var scope = globalProvider.CreateScope())
{
    var localScoped = scope.ServiceProvider.GetService<ExampleService>();

    var globalScoped = globalProvider.GetService<ExampleService>();
}

可以轻松测试:

using (var scope = globalProvider.CreateScope())
{
    var localScopedV1 = scope.ServiceProvider.GetService<ExampleService>();
    var localScopedV2 = scope.ServiceProvider.GetService<ExampleService>();
    Assert.Equal(localScopedV1, localScopedV2);

    var globalScoped = globalProvider.GetService<ExampleService>();
    Assert.NotEqual(localScopedV1, globalScoped);
    Assert.NotEqual(localScopedV2, globalScoped);
}

文档:Service Lifetimes and Registration Options.

引用Microsoft.Extensions.DependencyInjection 或者只是 Microsoft.AspNetCore.All 使用上面代码的包。