We’re introducing a lot of terms here, so for recap:
- The Dependency Inversion Principle (DIP) attempts to define and resolve the dependency problem through use of abstraction (interfaces).
- The Inversion of Control principle attempts to resolve the dependency problem by moving control of dependencies to a separate class.
- Dependency Injection is one of many design patterns that implements the IoC principle.
Let’s try to put it all together. In the code editor, you can see that the original version of
Trainer is already in the code. We’ll update it to use the new version.
In ISpeaker.cs, define an interface
ISpeaker with one method:
void Speak(string message);
In LoudSpeaker.cs and QuietSpeaker.cs, use the colon syntax to make each “Speaker” class implement
In Trainer.cs, change the type of
In Trainer.cs, set up the constructor for dependency injection:
- Add an
- Store the parameter’s value in
In Program.cs, inject a
LoudSpeaker object into the
LoudSpeaker with a
QuietSpeaker and see that the code runs without error.