问题
使用默认的 Asp.net Core IoC 容器,我是否可以保证如果为一个接口(interface)注册了多个对象类型并且我为该接口(interface)请求服务,IoC 将始终返回为该接口(interface)注册的最后一个对象类型?
(我通读了 .Net Core 依赖注入(inject)文档,它似乎没有解决这个问题。https://learn.microsoft.com/en-us/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;
}
}
现在,在 Startup.cs 的 ConfigureServices
方法中,我添加了以下代码:
services.AddSingleton<ITest, TestTwo>();
services.AddSingleton<ITest, TestThree>();
services.AddSingleton<ITest, TestOne>();
在startup.cs的Configure
方法中,如果我写了下面的代码:
var serviceCollection = app.ApplicationServices.GetServices<ITest>();
我得到了这些对象的集合:TestTwo
、TestThree
和 TestOne
,按顺序排列。
在 startup.cs Configure
方法中,如果我编写以下代码:
var service = app.ApplicationServices.GetService<ITest>();
它似乎总是返回为接口(interface)注册的最后一个对象的实例,在本例中为 TestOne
。
我能保证如果为一个接口(interface)注册了多个对象类型并且我为该接口(interface)请求服务,IoC 将总是返回为该接口(interface)注册的最后一个对象类型吗?
最佳答案
我想说获得最后一个是有保证的。如果你看the source code你可以看到当前的行为:
// internal class ServiceProvider
ServiceEntry entry;
if (_table.TryGetEntry(serviceType, out entry))
{
return GetResolveCallSite(entry.Last, callSiteChain);
}
如果 Microsoft 将来更改此行为,那将是一个重大的突破性更改,不仅会影响 .NET Core DI 容器的客户端,还会影响第 3 方容器的所有适配器的客户端。
它也会破坏适配器,因为 .NET Core 容器的行为决定了 DI 抽象的契约,这也会波及到适配器。
由于这种破坏性变化非常严重,他们永远无法改变这种行为,这意味着这种行为是有保证的。
关于c# - .Net 核心服务容器,我能保证为接口(interface)注册最后一个服务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564153/