为多个 HTTP 请求共享相同的 DbContext

Same DbContext shared for multiple HTTP requests

当两个并发请求发送到我的 ASP.NET MVC Web 应用程序时,我收到以下异常。我通过同时从桌面和移动登录来模拟这一点。

There is already an open DataReader associated with this Command which must be closed first.

我正在使用 Autofac 注册 DbContextRepositoriesServices

builder.RegisterType<DbContext>().As<IDbContext>().Named<IDbContext>("appdb").InstancePerRequest();
builder.RegisterType<LogDbContext>().As<IDbContext>().Named<IDbContext>("applogdb").InstancePerRequest();
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerRequest();

也正在注册为每个唯一的 HTTP 请求创建的服务。

builder.RegisterType<ProductService>().As<IProductService>().InstancePerRequest();
builder.RegisterType<CategoryService>().As<ICategoryService>().InstancePerRequest();
builder.RegisterType<ProductLineService>().As<IProductLineService>().InstancePerRequest();
builder.RegisterType<PatientService>().As<IPatientService>().InstancePerRequest();
builder.RegisterType<CommonService>().As<ICommonService>().InstancePerRequest();

我的理解是,我收到错误是因为在请求(根范围)之间共享同一个 DbContext 实例。

这没有意义,因为我已经注册了我的 DbContext 实例来为每个 HTTP 请求创建一个唯一的实例。

我唯一注册的单例对象是缓存管理器class。

正如您在评论中提到的,即使您设置了 InstancePerRequest,也请使用 MultipleActiveDataSets = true

您正在为 DbContext 的每个请求创建一个实例,但 SQL 服务器接口通过多个线程共享相同的连接以减少资源使用。

此外,EF 正在为延迟加载共享资源(另请参阅@gert-arnold 的评论)

在花了 10 个小时认为它与 EF 相关之后,我决定看看我是如何解决的 IDbContext

问题是我没有从名为“AutofacWebRequest”的 HTTP 请求容器中解析 IDbContext。它没有为每个 HTTP 请求创建一个实例,因此导致了错误。这是一个依赖注入相关的问题。