How can I take advantage of the DbContext Pooling out of ASP.NET Core LifeCycle?

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

Accepted Answer

I was able to resolve my problem or obtain an answer by asking the inquiry. The following was tried using threads that weren't part of a request.

It turns out that we can use the API to inject the service provider and create our own instances!

ReadOnly IServiceProvider _ServiceProvider;

MySingulation(IServiceProvider serviceProvider)
{
    _ServiceProvider = serviceProvider;
}

We can utilize the MVC Core API to construct instances of our context after we have a hold on IServiceProvider via injection.

using(var serviceScope = _ServiceProvider.CreateScope())
{
    // Don't get confused -- Call GetService from the serviceScope and 
    // not directly from the member variable _ServiceProvider. 
    var context = serviceScope.ServiceProvider.GetService<YourAppDbContext>();

    // ...
    // Make use of the dbcontext
    // ...

}

Now, it's crucial to keep in mind that we first used MVC Core Pooling in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddDbContextPool<YourAppDbContext>(options => {
        options.UseSqlServer(settings.Connection);
    });

    // Oh, it's important the singultion was created within Core's LifeCycle/API
    services.AddSingleton<MySingulation>();
    //...
}   
1
3/30/2019 8:50:37 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