using Microsoft.Extensions.DependencyInjection; namespace Managing.Core { public static class ServiceScopeHelpers { public static async Task WithScopedService(IServiceScopeFactory scopeFactory, Func action) where TService : notnull { using var scope = scopeFactory.CreateScope(); var service = scope.ServiceProvider.GetRequiredService(); await action(service); } public static async Task WithScopedService(IServiceScopeFactory scopeFactory, Func> action) where TService : notnull { using var scope = scopeFactory.CreateScope(); var service = scope.ServiceProvider.GetRequiredService(); return await action(service); } public static async Task WithScopedServices(IServiceScopeFactory scopeFactory, Func action) where T1 : notnull where T2 : notnull { using var scope = scopeFactory.CreateScope(); var s1 = scope.ServiceProvider.GetRequiredService(); var s2 = scope.ServiceProvider.GetRequiredService(); await action(s1, s2); } public static async Task WithScopedServices(IServiceScopeFactory scopeFactory, Func> action) where T1 : notnull where T2 : notnull { using var scope = scopeFactory.CreateScope(); var s1 = scope.ServiceProvider.GetRequiredService(); var s2 = scope.ServiceProvider.GetRequiredService(); return await action(s1, s2); } public static async Task WithScopedServices(IServiceScopeFactory scopeFactory, Func action) where T1 : notnull where T2 : notnull where T3 : notnull { using var scope = scopeFactory.CreateScope(); var s1 = scope.ServiceProvider.GetRequiredService(); var s2 = scope.ServiceProvider.GetRequiredService(); var s3 = scope.ServiceProvider.GetRequiredService(); await action(s1, s2, s3); } public static async Task WithScopedServices(IServiceScopeFactory scopeFactory, Func> action) where T1 : notnull where T2 : notnull where T3 : notnull { using var scope = scopeFactory.CreateScope(); var s1 = scope.ServiceProvider.GetRequiredService(); var s2 = scope.ServiceProvider.GetRequiredService(); var s3 = scope.ServiceProvider.GetRequiredService(); return await action(s1, s2, s3); } } }