使用默认的Asp.net Core IoC容器,是否可以保证如果为一个接口注册了多种对象类型,并且我要求该接口提供服务,则IoC将始终返回为该接口注册的最后一个对象类型?
(我阅读了.Net核心依赖项注入文档,但似乎没有解决此问题。https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection)
假设我有这个介面:
interface ITest
{
void Create(int id);
}
这些类:
public class TestOne: ITest {
int id;
public void Create(int id) {
this.id = id;
}
}
public class TestTwo: ITest {
int id;
public void Create(int id) {
this.id = id;
}
}
public class TestThree: ITest {
int id;
public void Create(int id) {
this.id = id;
}
}
现在,在该ConfigureServices
方法的Startup.cs中,添加以下代码:
services.AddSingleton<ITest, TestTwo>();
services.AddSingleton<ITest, TestThree>();
services.AddSingleton<ITest, TestOne>();
在startup.csConfigure
方法中,如果我编写以下代码:
var serviceCollection = app.ApplicationServices.GetServices<ITest>();
我去问对象的集合:TestTwo
,TestThree
并TestOne
按此顺序。
在startup.csConfigure
方法中,如果我编写以下代码:
var service = app.ApplicationServices.GetService<ITest>();
在这种情况下,似乎总是返回为该接口注册的最后一个对象的实例TestOne
。
我是否可以保证如果为一个接口注册了多个对象类型,并且要求该接口提供服务,则IoC总是会返回为该接口注册的最后一个对象类型?
我想说,获得最后一个是有保证的。如果查看源代码,则可以看到当前行为:
// internal class ServiceProvider
ServiceEntry entry;
if (_table.TryGetEntry(serviceType, out entry))
{
return GetResolveCallSite(entry.Last, callSiteChain);
}
如果Microsoft将来改变这种行为,那将是一个重大的突破性变化,不仅会影响.NET Core DI容器的客户端,而且还会影响第三方容器的所有适配器的客户端。
这也会破坏适配器,因为.NET Core容器的行为决定了DI抽象的协定,并且这也波及到适配器。
由于这种重大变化将是非常严重的,因此他们永远无法更改此行为,这意味着该行为得到了保证。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句