替换 ASP.NET Core 内置 DI 容器中的服务注册? [英] Replace service registration in ASP.NET Core built-in DI container?

查看:29
本文介绍了替换 ASP.NET Core 内置 DI 容器中的服务注册?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑在 Startup.ConfigureServices 中的服务注册:

Let us consider a service registration in Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IFoo, FooA>();
}

是否可以在调用 AddTransient 后将 IFoo 注册更改为 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 返回 FooB 而不是 FooA:

Then GetService<IFoo> returns FooB instead of FooA:

IFoo service = services.BuildServiceProvider().GetService<IFoo>();
Assert.True(service is FooB);

然而,GetServices 成功返回了两个实现(对于 GetService> 也是如此):

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);

IServiceCollection 合约中有 Remove(ServiceDescriptor) 方法.我应该如何使用 ServiceDescriptor 来修改服务注册?

There is Remove(ServiceDescriptor) method in IServiceCollection contract. What should I do with ServiceDescriptor to modify a service registration?

推荐答案

这很简单,使用 Replace(IServiceCollection, ServiceDescriptor) 方法来自 ServiceCollectionDescriptorExtensions 类.

This is simple using the Replace(IServiceCollection, ServiceDescriptor) method from the ServiceCollectionDescriptorExtensions class.

// IFoo -> FooA
services.AddTransient<IFoo, FooA>();

// Replace
// IFoo -> FooB
var descriptor =
    new ServiceDescriptor(
        typeof(IFoo),
        typeof(FooB),
        ServiceLifetime.Transient);
services.Replace(descriptor);

另见:

这篇关于替换 ASP.NET Core 内置 DI 容器中的服务注册?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆