替换ASP.NET Core内置DI容器中的服务注册? [英] Replace service registration in ASP.NET Core built-in DI container?
问题描述
让我们考虑在 Startup.ConfigureServices
中进行服务注册:
Let us consider a service registration in Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IFoo, FooA>();
}
是否可以更改 IFoo $ c在调用
中注册$ c>?对于测试目的(例如,在 AddTransient
之后,如何在$ c> FooB TestStartup
子类中)或我们对代码库的访问受限制的情况,这可能会有所帮助。
Is it possible to change IFoo
registration to FooB
after AddTransient
has been called? It can be helpful for testing purposes (for example, in TestStartup
subclass) or if our access to codebase is limited.
如果我们注册另一个 IFoo
实现:
If we register another IFoo
implementation:
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>>
都是相同的):
However, GetServices<IFoo>
successfully returns both implementations (and the same for GetService<IEnumerable<IFoo>>
):
var list = services.BuildServiceProvider().GetServices<IFoo>().ToList();
Assert.Equal(2, list.Count);
其中有 Remove(ServiceDescriptor)
方法 IServiceCollection
合同。我应该如何使用 ServiceDescriptor
修改服务注册?
There is Remove(ServiceDescriptor)
method in IServiceCollection
contract. What should I do with ServiceDescriptor
to modify a service registration?
推荐答案
使用 <$ c $来自 ServiceCollectionDescriptorExtensions
类。
// IFoo -> FooA
services.AddTransient<IFoo, FooA>();
// Replace
// IFoo -> FooB
var descriptor =
new ServiceDescriptor(
typeof(IFoo),
typeof(FooB),
ServiceLifetime.Transient);
services.Replace(descriptor);
另请参见:
- ServiceDescriptor constructors
这篇关于替换ASP.NET Core内置DI容器中的服务注册?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!