首页 > 解决方案 > 当有多个实现接口的类时,如何指定构造函数注入

问题描述

我想对在其构造函数中采用接口 IService 的类使用依赖注入。但是我有这个接口的几个实现。其他类也需要这两种实现,所以我不能简单地只启动需要的那个。我正在使用 Microsoft.Extensions.DependencyInjection

这是一个尝试显示我的课程的示例

public interface IService { }

public class ServiceA : IService { ... }

public class ServiceB : IService { ... }

public class Foo
{
    public Foo(IService service) { }
}

public class Bar
{
    public Bar(IService service)  { }
}

如果我没有几个实现,我会像下面这样注入它:

builder.Services.AddSingleton<IService, ServiceA>();
builder.Services.AddSingleton<Foo>();

在示例中,我需要使用 ServiceA 初始化 Foo,使用 ServiceB 初始化 Bar。

标签: c#dependency-injection

解决方案


像这样(直接在浏览器中输入):

builder.Services.AddSingleton<ServiceA>();
builder.Services.AddSingleton<ServiceB>();
builder.Services.AddSingleton<Foo>(c =>
    ActivatorUtilities.CreateInstance<Foo>(c, c.GetRequiredService<ServiceA>())); 
builder.Services.AddSingleton<Bar>(c =>
    ActivatorUtilities.CreateInstance<Bar>(c, c.GetRequiredService<ServiceB>())); 

推荐阅读