Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class HostedWorker : BackgroundService
- {
- private readonly IServiceScopeFactory scopeFactory;
- public HostedWorker(IServiceScopeFactory scopeFactory)
- {
- this.scopeFactory = scopeFactory;
- }
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
- using (var scope = scopeFactory.CreateScope())
- {
- var database = scope.ServiceProvider
- .GetRequiredService<DatabaseContext>();
- var entity = database.GetSomeEntity();
- scope.ServiceProvider
- .GetRequiredService<ISomeScopedService>()
- .DoSomethingWithTheEntity(entity)
- }
- }
- }
- public class SomeScopedService: ISomeScopedService
- {
- private readonly DatabaseContext context;
- public SomeScopedService(DatabaseContext context)
- {
- this.context = context;
- }
- public void DoSomethingWithTheEntity(SomeEntity entity)
- {
- // the context doesn't track the entity
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement