Learn
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.
Instructions
1.
In ISpeaker.cs, define an interface ISpeaker
with one method:
void Speak(string message);
2.
In LoudSpeaker.cs and QuietSpeaker.cs, use the colon syntax to make each “Speaker” class implement ISpeaker
.
3.
In Trainer.cs, change the type of _speaker
from LoudSpeaker
to ISpeaker
.
4.
In Trainer.cs, set up the constructor for dependency injection:
- Add an
ISpeaker
parameter - Store the parameter’s value in
_speaker
5.
In Program.cs, inject a LoudSpeaker
object into the Trainer
instance.
6.
Replace the LoudSpeaker
with a QuietSpeaker
and see that the code runs without error.
Sign up to start coding
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.