我想问一下在组件之间利用数据库上下文的最佳实践是什么? Blazor 服务器、.Net 5、EF Core 5.0.8
情况简介:
组件a, header
组件 b,主要
DbContext 被注册为 Transient,并且 Header 和 Main 都有自己的上下文。
但是在例如:更改 Main 中的数据之后,它不会应用于 Header,因此数据变得不一致。
想法:
1、删除 DbContext 注册并为每个数据库调用手动创建一个新的
2、保留当前架构,但添加额外的调用来刷新数据(需要时)
3、将DbContext注册为Scoped并围绕它构建某种队列服务来逐步处理查询(避免并发调用)并通过EventAggregator消息返回结果。
您怎么看,如何处理这种情况?
最佳答案
根据@Liero的回答,我最初还应用了 IDbContextFactory 来为数据库的每个服务调用创建一个新的上下文实例 - 但是,对于我的应用程序,我需要跨多个组件进行更改跟踪,但我不希望打破工作单元模式,因为这会导致数据库不一致的一些问题。
正如您在步骤(3)中提到的 - 我将 DbContext 保留为范围(据我所知这是默认值),然后我使用 semaphore防止线程问题:
@code {
static Semaphore semaphore;
//code ommitted for brevity
protected override async Task OnInitializedAsync()
{
try
{
//First open global semaphore
semaphore = Semaphore.OpenExisting("GlobalSemaphore");
while (!semaphore.WaitOne(TimeSpan.FromTicks(1)))
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
//If while loop is exited or skipped, previous service calls are completed.
ApplicationUsers = await ApplicationUserService.Get();
}
finally
{
try
{
semaphore.Release();
}
catch (Exception ex)
{
Console.WriteLine("ex.Message");
}
}
}
这对于我需要跨组件保留更改跟踪的特定用例来说非常有效。 Here's my full answer from another related question.
关于entity-framework-core - Blazor Server 组件之间的数据库上下文保持一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68681120/