[英]ServiceProvider.GetService returns the same instance for scoped service in transient instance factory
In asp.net core 3.1 project, I have the following controller (ctor):在 asp.net core 3.1 项目中,我有以下控制器(ctor):
public MyController(IMyService myService) { }
The IMyService
interface and MyService
IMyService
接口和MyService
public interface IMyService { }
public class MyService : IMyService { }
Where the IService
is registered in my Startup.cs
as follows: IService
在我的Startup.cs
注册如下:
services.AddScoped<MyService>();
services.AddTransient(sp =>
{
var service = sp.GetRequiredService<MyService>();
// do something on the service...
return service as IMyService;
});
However, when I'm doing multiple requests, I see that only the first request is initiating a new instance of the MyService
(ie, when I'm putting a breakpoint in the MyService
constructor, it will break only on the first request).但是,当我执行多个请求时,我看到只有第一个请求正在启动MyService
的新实例(即,当我在MyService
构造函数中放置断点时,它只会在第一个请求时中断)。
The thing that bugs me the most, is that if I'm changing the services.AddTransient(sp => ...
line in the Startup.cs
file to services.AddScoped(sp => ...
- everything works and the instance is initiated every request.最让我烦恼的是,如果我将Startup.cs
文件中的services.AddTransient(sp => ...
行更改为services.AddScoped(sp => ...
- 一切正常,实例每次请求都会发起。
How can I fix the issue so when I'm getting services inside the instance factory, it will be gathered by the correct scope of the request?我该如何解决这个问题,以便当我在实例工厂中获取服务时,它将由请求的正确范围收集?
Following @GuruStron comment, I found out that I have the following line in my Program.cs
, although I'm not really using Unity container in my project:在@GuruStron 评论之后,我发现我的Program.cs
有以下行,尽管我并没有在我的项目中真正使用 Unity 容器:
.UseUnityServiceProvider()
after I removed this line, everything works as expected.删除此行后,一切都按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.