英文:
Dynamic AddDbContext and async service
问题
我的Net 7 API应用程序是多租户的。
我在Program.cs中使用以下代码管理连接字符串的更改:
builder.Services.AddDbContext<IDbContext, DbContext>((services, options) =>
{
var tenantService = services.GetRequiredService<ITenantService>();
var tenantConnectionString = tenantService.GetConnectionString();
options.UseSqlServer(tenantConnectionString, x => x.UseHierarchyId().UseNetTopologySuite())
.ConfigureWarnings(x => x.Ignore(CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning));
});
我有一个TenantService,它通过检查令牌中的声明返回租户的数据库连接字符串。一切都正常工作。
现在,我启动了一个新项目,其中需要从我使用以下代码调用的外部API中读取ConnectionString:
await httpClient.GetAsync(url)
这个调用使整个场景变成了异步的,所以我遇到了一些与之前配置相关的问题。
在这种情况下,我应该异步检索tenantService。我应该如何做到这一点?
英文:
My Net 7 API application is multitenant.
I manage the change of the connection string in Program.cs with this code:
builder.Services.AddDbContext<IDbContext, DbContext>((services, options) =>
{
var tenantService = services.GetRequiredService<ITenantService>();
var tenantConnectionString = tenantService.GetConnectionString();
options.UseSqlServer(tenantConnectionString, x => x.UseHierarchyId().UseNetTopologySuite())
.ConfigureWarnings(x => x.Ignore(CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning));
});
I have a TenantService which returns the database connection string for the tenant by examining a claim present in the token. Everything is working correctly.
Now, I have started a new project where the retrieval of the ConnectionString is slightly different because it needs to be read from an external API that I invoke using
await httpClient.GetAsync(url)
This call makes the entire scenario asynchronous, so I have some issues with the previous configuration.
In this case, I should retrieve the tenantService asynchronously. How can I do that?
答案1
得分: 3
如果您的意思是URL在启动期间仅检索一次,那么您可以同步执行它,并保持其余代码不变。
如果URL完全动态,并且您在运行时有多个值,那么标准做法是引入工厂类型,并使用它来代替直接注入数据库上下文。
英文:
If you mean the url is retrieved once during startup, then you can do it synchronously, and keep the rest of the code the same.
If the url is fully dynamic and you'll have multiple values at runtime, then the standard practice is to introduce a factory type and use that instead of injecting a db context directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论