【发布时间】:2021-02-07 13:28:19
【问题描述】:
我有一个 .Net Core 3.1 Web API,我有以下依赖项:
- 作为 Scoped
SomeDbContext(使用 AddDbContextPool)。 - 作为Transient
SomeDbRepository,接收上述SomeDbContext。 - 作为Transient
SomeService,接收上述SomeDbRepository。 - 作为
SomeService的Singleton工厂。
这里是在 Startup.cs 中注入依赖的代码
services.AddDbContextPool<SomeDbContext>(options => options.UseSqlServer("connectionsString"));
services.AddTransient<SomeDbRepository>();// recive SomeDbContext
services.AddTransient<SomeService>();// recive SomeDbRepository
//Factory for SomeService
services.AddSingleton<Func<SomeService>>(provider => () =>
{
return provider.GetService<SomeService>();
});
API 控制器
//API Controller
public SomeController(Func<SomeService> factory)
{
_someService = factory.Invoke();
}
当我在多线程环境中调用我的 API 时出现错误:
错误:在前一个操作之前在此上下文上启动了第二个操作 完全的。这通常是由于不同的线程使用相同的 DbContext 实例
为什么我的 DbContext 被不同的线程使用?它假设工厂为每个请求返回一个新的作用域 DbContext。我只使用(调用)工厂一次 por 请求。
如果我将工厂的生命周期从 Sinlgeton 更改为 Scoped,它可以正常工作。但我不知道为什么?为什么会影响工厂的生命周期?有人可以解释一下为什么它会这样工作。非常感谢大家!!
【问题讨论】:
-
调试代码时是否看到调用了工厂?
-
@Alexei Levenkov 是的,每次请求都会调用工厂。当我调试时,我会根据每个请求进入工厂。
标签: c# multithreading asp.net-core .net-core dependency-injection