Skip to content

Instantly share code, notes, and snippets.

@hd9
Created October 18, 2019 17:42
Show Gist options
  • Save hd9/922aa3f527f09138b8b08b6965263b12 to your computer and use it in GitHub Desktop.
Save hd9/922aa3f527f09138b8b08b6965263b12 to your computer and use it in GitHub Desktop.
Accessing Entity Framework context on the background on .NET Core
// Step 3 - Resolve the service from the background task
// Source: https://blog.hildenco.com/2018/12/accessing-entity-framework-context-on.html
private async Task BgTask(string id, IServiceScopeFactory serviceScopeFactory)
{
await Task.Delay(30000);
using (var scope = serviceScopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>();
dbContext.MyTable.Add(new MyObject { Id = "c6334a9e-4e7a-48bd-9b65-290c92b85f6f", Message = "Test bg thread" });
await dbContext.SaveChangesAsync();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment