使用AddDbContextPool时使用DbContext的多个实例

我在ASP.NET Core 3.1 Web服务器中使用GraphQL的实现。它在同一请求中执行多个通过依赖项注入需要DbContext的解析器方法。以前,我曾经将AddDbContext设置为contextLifetime的情况下配置ServiceLifetime.Transient,以避免对同一DbContext进行并行操作。现在,我想切换到AddDbContextPool以在请求之间以及在同一请求中重用DbContext的实例。有办法以某种方式实现这一目标吗?

fjbtxf 回答:使用AddDbContextPool时使用DbContext的多个实例

默认情况下,在原始实现中,AddDbContextPool使用AddScoped

public static IServiceCollection AddDbContextPool<TContextService,TContextImplementation>(
      [NotNull] this IServiceCollection serviceCollection,[NotNull] Action<IServiceProvider,DbContextOptionsBuilder> optionsAction,int poolSize = 128)
      where TContextService : class
      where TContextImplementation : DbContext,TContextService
    {
      Check.NotNull<IServiceCollection>(serviceCollection,nameof (serviceCollection));
      Check.NotNull<Action<IServiceProvider,DbContextOptionsBuilder>>(optionsAction,nameof (optionsAction));
      if (poolSize <= 0)
        throw new ArgumentOutOfRangeException(nameof (poolSize),CoreStrings.InvalidPoolSize);
      EntityFrameworkServiceCollectionExtensions.CheckContextConstructors<TContextImplementation>();
      EntityFrameworkServiceCollectionExtensions.AddCoreServices<TContextImplementation>(serviceCollection,(Action<IServiceProvider,DbContextOptionsBuilder>) ((sp,ob) =>
      {
        optionsAction(sp,ob);
        CoreOptionsExtension extension = (ob.Options.FindExtension<CoreOptionsExtension>() ?? new CoreOptionsExtension()).WithMaxPoolSize(new int?(poolSize));
        ((IDbContextOptionsBuilderInfrastructure) ob).AddOrUpdateExtension<CoreOptionsExtension>(extension);
      }),ServiceLifetime.Singleton);
      serviceCollection.TryAddSingleton<DbContextPool<TContextImplementation>>((Func<IServiceProvider,DbContextPool<TContextImplementation>>) (sp => new DbContextPool<TContextImplementation>((DbContextOptions) sp.GetService<DbContextOptions<TContextImplementation>>())));

      //SEE THIS LINE HERE
      serviceCollection.AddScoped<DbContextPool<TContextImplementation>.Lease>();


      serviceCollection.AddScoped<TContextService>((Func<IServiceProvider,TContextService>) (sp => (TContextService) sp.GetService<DbContextPool<TContextImplementation>.Lease>().Context));
      return serviceCollection;
    }

在您的 ConfigureServices 上添加AddDbContextPool应该足够

services.AddDbContextPool<YardCheckDBContext>(options => options.UseSqlServer(connection));

此外,它还可以帮助您提高每秒的平均请求数,有关更多参考,请参见本文,在本文中您可以找到是否使用DbContextPool进行比较。 希望对您有帮助

DbContext Pool

本文链接:https://www.f2er.com/2778836.html

大家都在问