Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface IServiceScopeFactory<T> where T : class
- {
- IServiceScope<T> CreateScope();
- }
- public interface IServiceScope<T> : IDisposable where T : class
- {
- T Service { get; }
- }
- public class ServiceScopeFactory<T> : IServiceScopeFactory<T> where T:class
- {
- private readonly IServiceScopeFactory _serviceScopeFactory;
- public ServiceScopeFactory(IServiceScopeFactory serviceScopeFactory)
- {
- _serviceScopeFactory = serviceScopeFactory;
- }
- public IServiceScope<T> CreateScope()
- {
- return new ServiceScope<T>(_serviceScopeFactory.CreateScope());
- }
- }
- public class ServiceScope<T> : IServiceScope<T> where T : class
- {
- private readonly IServiceScope _scope;
- private T _service;
- public ServiceScope(IServiceScope scope)
- {
- _scope = scope;
- }
- public void Dispose()
- {
- _scope?.Dispose();
- }
- public T Service => _service ?? (_service = _scope.ServiceProvider.GetRequiredService<T>());
- }
- public class Foo
- {
- private readonly IServiceScopeFactory<ConmaniaDbContext> _dbContextFactory;
- public Foo(IServiceScopeFactory<ConmaniaDbContext> dbContextFactory)
- {
- _dbContextFactory = dbContextFactory;
- }
- public void Bar()
- {
- using (var scope = _dbContextFactory.CreateScope())
- {
- var dbContext = scope.Service
- //use service
- }
- }
- }
- public static void AddServiceScopeFactory<T>(this IServiceCollection serviceCollection) where T : class
- {
- serviceCollection.AddTransient<IServiceScopeFactory<T>, ServiceScopeFactory<T>>();
- }
- services.AddScoped<ConmaniaDbContext, ConmaniaDbContext>(); //Scoped Service
- services.AddServiceScopeFactory<ConmaniaDbContext>();
- services.AddSingleton<Foo, Foo>(); //Singleton Service
- public class Foo
- {
- private readonly IServiceScopeFactory _scopeFactory;
- public Foo(IServiceScopeFactory scopeFactory)
- {
- _scopeFactory = scopeFactory;
- }
- public void Bar()
- {
- using (var scope = _scopeFactory.CreateScope())
- {
- var dbContext = scope.ServiceProvider.GetRequiredService<ConmaniaDbContext>()
- //use service
- }
- }
- }
Add Comment
Please, Sign In to add comment