我正在构建一个控制台.NET Core应用程序.它会定期运行一个可以完成某些工作的方法.如何使ServiceProvider的行为与ASP.NET Core应用程序中的行为相同.我希望它在方法开始执行时解析作用域服务,并在方法结束时处理已解析的服务.
// pseudocode globalProvider.AddScoped<ExampleService>(); // ... using (var scopedProvider = globalProvider.CreateChildScope()) { var exampleService = scopedProvider.Resolve<ExampleService>(); }
参考
Microsoft.Extensions.DependencyInjection包并创建范围:
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); }