The DbContext of type cannot be pooled because it does not have a single public constructor accepting a single parameter of type DbContextOptions

前端 未结 5 634
青春惊慌失措
青春惊慌失措 2020-12-08 11:36

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

5条回答
  •  攒了一身酷
    2020-12-08 12:07

    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.

提交回复
热议问题