且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

替换 ASP.NET Core 内置 DI 容器中的服务注册?

更新时间:2023-02-15 23:20:38

这很简单,使用 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);

另见: