Configuring Dbcontext as Transient

C#asp.net CoreEntity Framework-Core

C# Problem Overview


In ASP.NET Core / EntityFramework Core, the services.AddDbContext<> method will add the specified context as a scoped service. It's my understanding that that is the suggested lifetime management for the dbcontext by Microsoft.

However, there is much debate in our engineer department over this and many feel that the context needs to be disposed of ASAP. So, what is the best way to configure the dbcontext as Transient that still maintains the same Repository pattern typically used (i.e. injecting the context directly into the repository's constructor) as well as supporting flexible unit testing?

C# Solutions


Solution 1 - C#

The lifetime is a parameter on AddDbContext<>(). See example:

services.AddDbContext<ApplicationDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), 
         ServiceLifetime.Transient);

This will add it to the service collection with transient lifetime.

Solution 2 - C#

In my opinion, a good use case for registering a DbContext as a transient dependency is within worker services that are registered as singletons. You can not use scoped dependencies within singleton dependencies. So the only option you have is to register the DbContext as either singleton or transient. Something to bear in mind is that the injected DbContextOptions class lifetime also needs to be updated. You can do both by specifying the service lifetime as follows.

services.AddDbContext<DataContext>(options =>
        {
            options.UseMySQL(configurationRoot.GetConnectionString("DefaultConnection"));
            options.UseLazyLoadingProxies();
        }, ServiceLifetime.Transient, ServiceLifetime.Transient);

The third parameter is for the service lifetime of the DbContextOptions instance.

Solution 3 - C#

You can also create a repository class and interface which has idbcontext constructor parameter. Have all of your controller constructors use this interface in their constructor. This can be added with addtransient. This way, Microsoft still controls the dbcontext as it sees fit. Context will be managed by runtime and injected when creating repository instances when creating controllers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJake ShakesworthView Question on Stackoverflow
Solution 1 - C#juunasView Answer on Stackoverflow
Solution 2 - C#SludgedogView Answer on Stackoverflow
Solution 3 - C#douglas.kirschmanView Answer on Stackoverflow