Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. public class HostedWorker : BackgroundService
  2. {
  3. private readonly IServiceScopeFactory scopeFactory;
  4.  
  5. public HostedWorker(IServiceScopeFactory scopeFactory)
  6. {
  7. this.scopeFactory = scopeFactory;
  8. }
  9.  
  10. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  11. {
  12. using (var scope = scopeFactory.CreateScope())
  13. {
  14. var database = scope.ServiceProvider
  15. .GetRequiredService<DatabaseContext>();
  16. var entity = database.GetSomeEntity();
  17. scope.ServiceProvider
  18. .GetRequiredService<ISomeScopedService>()
  19. .DoSomethingWithTheEntity(entity)
  20. }
  21. }
  22. }
  23.  
  24. public class SomeScopedService: ISomeScopedService
  25. {
  26. private readonly DatabaseContext context;
  27.  
  28. public SomeScopedService(DatabaseContext context)
  29. {
  30. this.context = context;
  31. }
  32.  
  33. public void DoSomethingWithTheEntity(SomeEntity entity)
  34. {
  35. // the context doesn't track the entity
  36. }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement