【问题标题】:How do I specify constructor injections when there's several classes that implements an interface [duplicate]当有多个实现接口的类时,如何指定构造函数注入[重复]
【发布时间】:2019-07-23 06:40:50
【问题描述】:

我想对在其构造函数中采用接口 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。

【问题讨论】:

  • 您将不得不进一步隔离您的 iterfaces,因此您的层次结构如下:ServiceA-&gt;IServiceA-&gt;IService。然后在注册时你会将你的服务绑定到 IServiceA 而不是 IService

标签: c# dependency-injection


【解决方案1】:

类似这样的东西(直接在浏览器中输入):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多