-1

Say I have this:

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
    }
}

Then I have two different implementations of the BreathingService...

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

How can I use DI to pass the correct service implementation to the associated object? Or do I have to specify an IHumanBreathingService and an IMartianBreathingService?

Jim W
  • 4,866
  • 1
  • 27
  • 43
David Cornelson
  • 391
  • 2
  • 3
  • 16

2 Answers2

0

Looks like Autofac - How to create a generated factory with parameters already answers this.

Autofac enables the ability to create a factory for creating the correct service.

David Cornelson
  • 391
  • 2
  • 3
  • 16
0

Your question lacks specificity therefore I will explicitly explain the assumption I am making.

Assumption 1: SentientLifeForm implements IBreathingService.

Assumption 2: HumanBreathingService and MartianBreathingService implement/derive-from IBreathingService.

Assumption 3: HumanBreathingService will be passed to the constructor for Human as a parameter and MartianBreathingService will be passed to the constructor for Martian as a parameter. THIS IS THE DI IN THIS PROJECT.

Thereafter, say you have a method SolarSystemBeing(..) that takes as an argument an instance of SentientLifeForm. Then depending on which instance it gets a Human or a martian the breathingService will be the appropriate one...

AviFarah
  • 327
  • 1
  • 10