How to get transient DbContext in ASP.NET MVC Core?

asp.net-core c# dependency-injection entity-framework-core

Question

I have the following in Startup.cs:

services.AddDbContext<MyDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("Sqlite")));

Now, I'd like to fire up an instance of MyDbContext that has a transient lifetime. The reason for doing so is because I'm populating my cache at startup. So how can I get an instance of MyDbContext that I'm responsible for disposing of myself? I have an IServiceProvider ready at hand.

serviceProvider.GetRequiredService<MyDbContext>();

throws an exception which says it's out of scope.

I understand why the exception is getting thrown, but I'm not sure what the best way of getting around it is.

1
3
12/10/2018 5:36:30 PM

Accepted Answer

You need to create a scope manually something like this:

using (var scope = serviceProvider.CreateScope())
{
    var scopedServices = scope.ServiceProvider; 
    scopedServices.GetRequiredService<MyDbContext>();

     ...
}

this will give a scoped dbcontext that will get automatically disposed by the scope closure when you are finished using it. During web requests there is a scope created automatically per request so it gets disposed at the end of the request.

6
12/10/2018 5:41:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow