在ASP.NET Core/EntityFramework Core中,services.AddDbContext <>方法将指定的上下文添加为作用域服务.我的理解是,这是Microsoft建议的dbcontext生命周期管理.
然而,我们的工程师部门对此有很多争论,许多人认为需要尽快处理上下文.那么,将dbcontext配置为Transient仍然保持通常使用的相同Repository模式(即将上下文直接注入存储库的构造函数)以及支持灵活的单元测试的最佳方法是什么?
我动态创建 NavMenu 并返回菜单我用户的数据库和索引页中我已经返回了数据库中的某些内容但是当我运行应用程序或重新加载它时会显示以下错误
InvalidOperationException:在上一个操作完成之前,在此上下文中启动了第二个操作。这通常是由使用相同 DbContext 实例的不同线程引起的。有关如何避免 DbContext 线程问题的详细信息,请参阅 https://go.microsoft.com/fwlink/?linkid=2097913。
导航菜单代码,
List<Menu> menus = new List<Menu>();
protected override async Task OnInitializedAsync()
{
menus = await MenuService.GetMenus();
}
Run Code Online (Sandbox Code Playgroud)
索引代码
@if (priorities == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
@foreach (var priority in priorities)
{
<tr>
<td>@priority.Name</td>
</tr>
}
</tbody>
</table>
}
@code {
List<Priority> priorities;
protected override async Task OnInitializedAsync()
{
priorities = await PriorityService.GetPriorities();
}
}
Run Code Online (Sandbox Code Playgroud)