在ConfigureServices中注册服务时将调用哪个构造函数 [英] Which constructor will be called when registering services in ConfigureServices
问题描述
如果我有一个类的两个构造函数,那么当我在ConfigureServices中注册该服务时,服务容器如何选择使用哪个?
If I have two constructors for a class, how does the service container choose which one to use when I'm registering that service in ConfigureServices?
所以可以说我有一个名为 MyClass
的类,具有相应的接口 IMyClass
。在 ConfigureServices()
方法中,我调用以下代码行
So lets say I have a class called MyClass
with a corresponding interface IMyClass
. In the ConfigureServices()
method I call the following line of code
services.AddScoped<IMyClass, MyClass>();
如果我具有以下构造函数,它将如何选择使用哪个构造函数?
How does it choose which constructor to use if I have the following constructors?
MyClass(ILogger logger)
MyClass(ILogger logger, IConfguration configuration)
推荐答案
构造函数匹配是通过称为 CallSiteFactory:CreateConstructorCallSite 。根据其源代码,该算法如下:
The constructor matching is performed by a method called CallSiteFactory:CreateConstructorCallSite. Based on its source code, the algorithm is the following:
- 查找目标类型为
的所有公共构造函数- 如果没有,则引发异常
- 如果只有一个,则使用它
- 选择参数个数最多的一个可以由DI注入
- 如果存在多个此类ctor,则抛出异常
要弄清楚何时可能存在歧义,请考虑以下因素:
To clarify when there can be an ambiguity, consider these ctors:
MyClass(ILogger logger) MyClass(IConfguration configuration)
DI引擎无法决定使用哪个引擎,因为两者都有可以注入的有效参数。
The DI engine can't decide which one to use, because both have valid parameters that can be injected.
在但是,在以下情况下,没有歧义,因为
int
类型未在DI引擎中注册,因此无法通过DI注入,因此第一个ctor将被选择:In the following case however, there's no ambiguity because the
int
type isn't registered in the DI engine, and thus can't be injected via DI, and thus the first ctor will be chosen:MyClass(ILogger logger) MyClass(int i)
所以回答您的问题:就您而言,第二个
So to answer your question: in your case, the second constructor will be used.
这篇关于在ConfigureServices中注册服务时将调用哪个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!