我在ASP.NET Core 3.1 Web服务器中使用GraphQL的实现。它在同一请求中执行多个通过依赖项注入需要DbContext
的解析器方法。以前,我曾经将AddDbContext
设置为contextLifetime
的情况下配置ServiceLifetime.Transient
,以避免对同一DbContext
进行并行操作。现在,我想切换到AddDbContextPool
以在请求之间以及在同一请求中重用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进行比较。 希望对您有帮助