1

我有一个自定义的 DbContext SnowflakeDbContext,我需要使用SnowflakeDbConnection对其进行初始化才能使其工作:

    public class SnowflakeDbContext : DbContext
    {
        private readonly string connectionString = "";

        public SnowflakeDbContext(DbContextOptions<SnowflakeDbContext> options) : base(options)
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            var dbConnection = new SnowflakeDbConnection()
            {
                ConnectionString = this.connectionString
            };
            optionsBuilder.UseSqlServer(dbConnection);
            optionsBuilder.AddInterceptors(new SnowflakeCommandInterceptor());
        }

        public DbSet<Opportunity> Opportunities { get; set; } = default!;
        public DbSet<Account> Accounts { get; set; } = default!;
    }

这适用于 EF Core 5,在 Startup.cs 中(我使用的是 ASP.NET Core 5 Web 应用程序)我使用

      .AddDbContext<SnowflakeDbContext>(ServiceLifetime.Singleton)

我想将SnowflakeDbContextHotChocolate一起使用,建议我使用AddPooledDbContextFactory<>以支持连接池并允许系统进行同时调用(在此处描述)。

我已经修改了 Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {

            services
                .AddPooledDbContextFactory<SnowflakeDbContext>(options =>
                {
                    var dbConnection = new SnowflakeDbConnection()
                    {
                        ConnectionString = this.connectionString
                    };

                    options.UseSqlServer(dbConnection);
                    options.AddInterceptors(new SnowflakeCommandInterceptor());
                })
                .AddGraphQLServer()
                .AddQueryType<Query>();
        }

使用以下 GraphQL 查询(使用并行查询):

query GetAccountsInParallel {
  a: accounts {
    id, name
  }
  b: accounts {
    id, name
  }
  c: accounts {
    id, name
  }
}

我收到以下错误:

"No service for type 'SnowflakeGraphQL.Snowflake.SnowflakeDbContext' has been registered.",

我可以加

      .AddDbContext<SnowflakeDbContext>()

在 Startup.cs 调用.AddPooledDbContextFactory<>之后。现在我得到一个不同的错误:

"A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext."

我在网上看到的所有示例都使用.UseSqlServer(connectionString),因为我需要使用.UseSqlServer(dbConnection)版本才能访问我们的 Snowflake 数据库。

如何在 Startup.cs 中配置我的应用程序以使用 .AddPooledDbContextFactory()?

更新:从 graphql-workshop 代码开始,用第一个 SqlServer 替换 Sqlite,然后使用我的 SnowflakeDbContext 替换 SqlServer 我让它工作,所以如上所述,我的代码中一定存在细微差别,导致我的案例失败。

4

1 回答 1

1

检索账户记录时,我们需要使用[ScopedService]而不是 [Service],如下所示:

   [UseApplicationDbContext]
   public async Task<List<Account>> GetAccounts([ScopedService] SnowflakeDbContext context) => await context.Accounts.ToListAsync();
于 2021-03-11T23:17:43.137 回答