Guest User

Untitled

a guest
Jan 20th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. public interface IServiceScopeFactory<T> where T : class
  2. {
  3. IServiceScope<T> CreateScope();
  4. }
  5.  
  6. public interface IServiceScope<T> : IDisposable where T : class
  7. {
  8. T Service { get; }
  9. }
  10.  
  11. public class ServiceScopeFactory<T> : IServiceScopeFactory<T> where T:class
  12. {
  13. private readonly IServiceScopeFactory _serviceScopeFactory;
  14.  
  15. public ServiceScopeFactory(IServiceScopeFactory serviceScopeFactory)
  16. {
  17. _serviceScopeFactory = serviceScopeFactory;
  18. }
  19.  
  20. public IServiceScope<T> CreateScope()
  21. {
  22. return new ServiceScope<T>(_serviceScopeFactory.CreateScope());
  23. }
  24. }
  25.  
  26. public class ServiceScope<T> : IServiceScope<T> where T : class
  27. {
  28. private readonly IServiceScope _scope;
  29. private T _service;
  30.  
  31. public ServiceScope(IServiceScope scope)
  32. {
  33. _scope = scope;
  34. }
  35.  
  36. public void Dispose()
  37. {
  38. _scope?.Dispose();
  39. }
  40.  
  41. public T Service => _service ?? (_service = _scope.ServiceProvider.GetRequiredService<T>());
  42. }
  43.  
  44. public class Foo
  45. {
  46. private readonly IServiceScopeFactory<ConmaniaDbContext> _dbContextFactory;
  47.  
  48. public Foo(IServiceScopeFactory<ConmaniaDbContext> dbContextFactory)
  49. {
  50. _dbContextFactory = dbContextFactory;
  51. }
  52.  
  53. public void Bar()
  54. {
  55. using (var scope = _dbContextFactory.CreateScope())
  56. {
  57. var dbContext = scope.Service
  58. //use service
  59. }
  60. }
  61. }
  62.  
  63. public static void AddServiceScopeFactory<T>(this IServiceCollection serviceCollection) where T : class
  64. {
  65. serviceCollection.AddTransient<IServiceScopeFactory<T>, ServiceScopeFactory<T>>();
  66. }
  67.  
  68. services.AddScoped<ConmaniaDbContext, ConmaniaDbContext>(); //Scoped Service
  69. services.AddServiceScopeFactory<ConmaniaDbContext>();
  70. services.AddSingleton<Foo, Foo>(); //Singleton Service
  71.  
  72. public class Foo
  73. {
  74. private readonly IServiceScopeFactory _scopeFactory;
  75.  
  76. public Foo(IServiceScopeFactory scopeFactory)
  77. {
  78. _scopeFactory = scopeFactory;
  79. }
  80.  
  81. public void Bar()
  82. {
  83. using (var scope = _scopeFactory.CreateScope())
  84. {
  85. var dbContext = scope.ServiceProvider.GetRequiredService<ConmaniaDbContext>()
  86. //use service
  87. }
  88. }
  89. }
Add Comment
Please, Sign In to add comment