Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContextScope Pattern for EF Core 3

Some of you may be familiar with the DbContextScope library, which allows you to nest scopes within your code, and allow those scopes to share a common DbContext. The idea is that the DbContext gets managed for you by the scope library, and instead of calling SaveChanges() on the context, you call SaveChanges() on the scope. The magic happens because the scope will only save all the changes on the context at it's outer-most call of SaveChanges(), so all the nested operations performed on the DbContext get saved in a single transaction at the outer scope-level.

Now that DI is a first-class citizen in .NET Core, it appears that scopes have also become an important part of the .NET Core ecosystem, and the EF Core team, knowing this, has implemented scoping based on allowing DbContexts being injected by the DI system, and (I assume) allowing change saving to happen at scope-levels and not directly on the DbContexts in some way.

So my question are these:

  • What is the appropriate way to share a DbContext via a scope, allowing the SaveChanges() be managed at the scope level and not the code-level that typically calls SaveChanges() on the DbContext?
  • Are there new mechanisms in EF Core that manage this for you, just like DbContextScope did this for you as a 3rd party library?
  • Save me the drama, and spare me the lectures on why you think UOW needs to be implemented in addition to EF. K thnxs bye.

UPDATE: As of 6/2020 there are several forks of DbContextScope that work with EF Core 3.

UPDATE: Forks of this project can be viewed here: https://github.com/mehdime/DbContextScope/network

There are several EF Core 3 versions... I haven't tried any yet, but there you go.

like image 646
Rafe Avatar asked Jun 02 '26 22:06

Rafe


1 Answers

Since Entity Framework 5.0.0, there is IDbContextFactory<TDbContext> that lets you control the creation and disposal (!!) of your DbContexts.

Instead of registering your DbContext with AddDbContext or AddDbContextPool, you can now use AddDbContextFactory or AddPooledDbContextFactory, respectively.

Note that this feature takes care of one of the problems that DbContextScope solves, not all of them. As for what the other problems and solutions are, refer to Mehdi's original post. It is long but excellent.

like image 110
Timo Avatar answered Jun 05 '26 10:06

Timo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!