What is the difference between instantiating DbContext and Getting DbContext service with IServiceScopeFactory in a hosted service

Viewed 39

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?

1 Answers

In general if you use dependency injection for the dbcontext it is scoped for the whole request. That means that using the dbcontext in different classes or methods will be using the same transaction which for example u can after all changes commit with .SaveChanges(). The dependency injection method is also good for making abstractions. If you create interface for your dbcontext then You can make two implementations - one will be your existing dbcontext and the other for example will not use the real database but some data in memory for the development.

If you use the using method then the transaction is within the using brackets and it's not accessible from multiple places but only in the place where it's instantiated and you are also tightly coupled with the framework.

Related