Search code examples
c#asp.net-coredependency-injectionentity-framework-core

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


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.


Solution

  • 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.