I am trying to upgrade our current .Net Core application from 1.1 to 2.0 and am getting this runtime error: \"The DbContext of type \'CoreContext\' cannot be pooled because
When using DbContext Pooling
, your own state (e.g. private fields) in your derived DbContext class will be preserved. Which means the lifetime of your services is now singleton
. That's why you shouldn't have other injected services here.
But it's possible to query the required services this way:
First we should use the UseInternalServiceProvider
method on DbContextOptionsBuilder
to tell EF which service provider to use for its services. This service provider must have all the services configured for EF and any providers. So we should register EF Services manually:
services.AddEntityFrameworkSqlServer();
And then introduce the application's services provider which now includes the EF Services too:
services.AddDbContextPool((serviceProvider, optionsBuilder) =>
{
optionsBuilder.UseSqlServer("...");
optionsBuilder.UseInternalServiceProvider(serviceProvider);
});
After that define these namespaces:
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
And now you can access the registered services in the application within the ApplicationDbContext class using the following methods
var siteSettings = this.GetService>();
Or
var siteSettings = this.GetInfrastructure().GetRequiredService>();
this
is the current instance of the DbContext.