I wanted to create a background task for my application and in that task I need DbContext to do some operation on data for every 5 seconds.I tried 2 way to get DbContext and it seems like both of them worked but I wanna now what is the difference between them(if there is any)
Here is the first approach
private readonly IServiceScopeFactory _serviceScopeFactory;
public worker(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
private void DoWork(object? state)
{
var scope = _serviceScopeFactory.CreateScope();
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
}
And this is the second approach that I tried
private void DoWork(object? state)
{
using (var db = new ApplicationDbContext(new DbContextOptions<ApplicationDbContext>()))
{
//do job
}
}
both of them seems working.Isn't both of them disposed and recreated when method called ? what is the difference? which one would you prefer and why?