基于接口的变构造函数依赖注入

时间:2017-11-15 14:03:45

标签: c# dependency-injection

说我有这个:

public class Human : SentientLifeForm, IHuman {
    IBreathingService breathingService = null;

    public Human(IBreathingService breathingService) {
        this.breathingService = breathingService
    }
}

public class Martian : SentientLifeForm, IMartian {
    IBreathingService breathingService = null;

    public Martian(IBreathingService breathingService) {
        this.breathingService = breathingService
    }
}

然后我有两种不同的BreathingService实现......

public class HumanBreathingService { ... }
public class MartianBreathingService { ... }

如何使用DI将正确的服务实现传递给关联对象?或者我是否必须指定IHumanBreathingService和IMartianBreathingService?

2 个答案:

答案 0 :(得分:0)

看起来Autofac - How to create a generated factory with parameters已经回答了这个问题。

Autofac可以创建工厂来创建正确的服务。

答案 1 :(得分:0)

你的问题缺乏特异性,因此我将明确解释我所做的假设。

假设1:SentientLifeForm实现IBreathingService。

假设2:HumanBreathingService和MartianBreathingService实现/派生自IBreathingService。

假设3: HumanBreathingService 将作为参数传递给 Human 的构造函数,而MartianBreathingService将传递给 Martian 的构造函数一个参数。 这是本项目中的DI

此后,假设您有一个方法SolarSystemBeing(..),它将SentientLifeForm的实例作为参数。然后根据它获得人类或火星的实例,呼吸服务将是合适的......

相关问题