AddSingleton()与AddSingleton()

编程入门 行业动态 更新时间:2024-10-17 11:30:28
本文介绍了AddSingleton()与AddSingleton()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在我的项目中实现依赖注入.我遇到了两种添加单例服务的方法-

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()

本文发布于:2023-11-13 14:56:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AddSingleton

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!