首页 > 解决方案 > 如何在 net core 3 中配置 Serilog MSSqlSink 为每个 Web 请求使用不同的连接字符串?

问题描述

我有一个访问单租户数据库的 .net core 3.1 多租户 Web API 应用程序。因此,每个请求都作用于n 个数据库中的任何一个。我配置了 EF Core DbContext,以便它从 http 请求中的声明中解析连接字符串,但我不知道为 Serilog 的 MSSqlSink 进行类似设置的正确方法。这是缩写的 DbContext 设置,可让您了解我要完成的工作:

        services.AddDbContext<MyContext>((serviceProvider, options) =>
        {
            // IHttpContextAccessor enables us to get at the claims
            var httpContext = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
            var httpRequest = httpContext.Request;

            var claim = httpContext.User.Claims.FirstOrDefault(x => x.Type == "MyClaim");
            var customerIdentifier = claim.Value;
            var connectionString = GetConnectionString(customerIdentifier);

            options.UseSqlServer(connectionString);
        });

到目前为止,我只能找到通过 appsettings 或环境变量使用已知的单个连接字符串设置 Serilog 的 MSSqlSink 的示例。

标签: sql-serverserilogasp.net-core-3.1

解决方案


推荐阅读