【发布时间】:2020-12-10 20:03:11
【问题描述】:
我是使用依赖注入的新手,在我真正开始使用它之前,我已经在我的 blazor 项目中走了很长一段路。
我将 DBContext 添加为瞬态服务(如这里的许多答案中所述)并将其注入 DataAccessLayer,如下所示:
public class DataAccessLayer
{
public DataAccessLayer(GlobalVariables s,DataContext d)
{
GlobalVariables = s;
context = d;
}
private readonly GlobalVariables GlobalVariables;
private readonly DataContext context;
`/other code here`
现在,当我打开一页时,我在我的 blazor 项目中使用 razor 组件,大约 5 个组件开始呈现。所有这些组件都从 DataAccessLayer 获取数据。
我遇到了这两个错误:
System.InvalidOperationException: Invalid attempt to call ReadAsync when reader is closed.
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext
当我删除依赖项并添加(使用 Datacontext)时,错误消失并且运行正常。有人可以建议我如何正确注射吗?
PS:我已经检查过我所有的异步方法都有 await 和 configureawait(true)
抛出 readasync 的第一个异常的方法是这样的:
public async Task<List<MasterCustomer>> getCustomersBinding()
{
List<MasterCustomer> customersList = new List<MasterCustomer>();
{
customersList = await (from table in context.MasterCustomer where (table.IsActive == true) select (new MasterCustomer { Code = table.Code, Name = table.Name })).ToListAsync().ConfigureAwait(true); ;
}
return customersList;
}
【问题讨论】:
-
你在哪里打电话给
ReadAsync?你能显示那个方法的代码吗 -
编辑问题以在其末尾添加询问的代码。
-
My answer 带有官方指南的链接,以将 EF 与 Blazor 服务器端结合使用。
标签: asp.net-core razor dependency-injection blazor dbcontext