A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913
问题出现场景
多线程操作EFCore 获取数据库上下文姿势不对;以下是正确姿势!
需求
使用 ef core v5.0.9 对数据库表新增数据。
多线程操作EFCore
步骤1:设置程序线程池最大化
1 | public static void Main(string[] args) |
有利于程序中线程创建速度加快。
步骤2:OrderingContext 数据上下文注入为瞬时
1 | public void ConfigureServices(IServiceCollection services) |
注入DbContext声明周期为, ServiceLifetime.Transient , 其他Ioc容器也设置为这个瞬时状态;
步骤3:仓储注入IServiceProvider
1 | public class OrderRepository : Repository<Order, OrderingContext>, IOrderRepository |
业务代码调用数据库上下文, 从_serviceProvider获取数据库上下文实例
1 | using (var ct = _serviceProvider.GetService<OrderingContext>()) |