问题描述
我正在我的项目中实现依赖注入.我遇到了两种添加单例服务的方法-
I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -
services.AddSingleton(new MyCustomService())
和
services.AddSingleton<MyCustomService>()
这两种方法似乎都有效.这两种方法有什么区别,我应该使用哪种方法?
Both methods seem to work. What's the difference between these two methods, and which one should I be using?
推荐答案
使用通用 .AddSingleton< TService>()
方法(和 .AddSingleton< TService,TImplementation>()时
,该类型由容器创建,控制和处理.当构造函数包含其他依赖项时,这些依赖项会自动注入(一种称为自动装配"的技术).
When using the generic .AddSingleton<TService>()
method (and .AddSingleton<TService, TImplementation>()
, the type is created, controlled, and disposed of by the container. When the constructor contains other dependencies, those dependencies are automatically injected (a technique called "Auto-Wiring").
使用 .AddSingleton< TService>(TService)
提供的实例已经存在.在这种情况下,当容器实现 IDisposable
或 IAsyncDisposable
时,该容器将不处置该实例.您有责任自己处置该实例.
Instances supplied using .AddSingleton<TService>(TService)
already exist. In that case, the container will not dispose of that instance when it implements IDisposable
or IAsyncDisposable
. You are responsible for disposing of that instance yourself.
由于 .AddSingleton< TService>(TService)
提供了一个已经存在的实例,因此该容器无法注入任何依赖关系,因为为此,它还必须 create实例.
Since .AddSingleton<TService>(TService)
is supplied with an already existing instance, the container can't inject any dependencies, because in order to do that, it must also create the instance.
这篇关于AddSingleton()与AddSingleton()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!