让我们考虑一下 Startup.ConfigureServices
中的服务注册:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IFoo, FooA>();
}
是否有可能在 AddTransient
被调用后将 IFoo
注册改为 FooB
?它可以有助于测试目的(例如,在 TestStartup
子类) ,或者如果我们的访问代码库是有限的。
如果我们注册另一个 IFoo
实现:
services.AddTransient<IFoo, FooA>();
services.AddTransient<IFoo, FooB>();
然后 GetService<IFoo>
返回 FooB
而不是 FooA
:
IFoo service = services.BuildServiceProvider().GetService<IFoo>();
Assert.True(service is FooB);
然而,GetServices<IFoo>
成功地返回了这两个实现(对于 GetService<IEnumerable<IFoo>>
也是一样的) :
var list = services.BuildServiceProvider().GetServices<IFoo>().ToList();
Assert.Equal(2, list.Count);
IServiceCollection
契约中有 Remove(ServiceDescriptor)
方法。我应该如何处理 ServiceDescriptor
来修改服务注册?