This blog article shows you how to create Dependency Injection using C#. Dependency Injection (DI) is a programming technique that allows objects to receive their dependencies from an external source rather than creating them internally. By doing so, it promotes flexibility, testability, and easier maintenance. DI helps decouple classes, making code more modular and adaptable.
The program without Dependency Injection.
The GameLoader class.
public class GameLoader
{
public string input { get; set; }
public GameLoader()
{
Console.WriteLine(“Enter the game you want to play: “);
}
public GameLoader(string input)
{
Console.WriteLine(“Enter the game you want to play: “);
this.input = input;
}
public void Load()
{
Console.WriteLine(“Loadinging ” + input);
}
}
The PlaystationConsole class.
internal class PlaystationConsole
{
GameLoader gameLoader = new GameLoader(“God of War”);
public void Play()
{
gameLoader.Load();
}
}
The main program.
static void Main(string[] args)
{
PlaystationConsole playstationConsole = new PlaystationConsole();
playstationConsole.Play();
}
As you can see, in order to change “God of War” I need to change in PlaystationConsole class.
Also: SOLID principle
The program with Dependency Injection.
The PlaystationConsole class.
internal class PlaystationConsole
{
GameLoader gameLoader = new GameLoader();
public PlaystationConsole(GameLoader gameLoaderr)
{
this.gameLoader = gameLoaderr;
}
public void Play()
{
gameLoader.Load();
}
}
The main program.
static void Main(string[] args)
{
PlaystationConsole playstationConsole = new PlaystationConsole(new GameLoader(“God of War”));
playstationConsole.Play();
}
In order to change “God of War” I no longer need to change anyclass implementation.
Source code download: https://github.com/chanmmn/general/tree/master/2024/DependencyInjection?WT.mc_id=DP-MVP-36769
Reference: https://www.youtube.com/watch?v=l7Gu_XrwtZE?WT.mc_id=DP-MVP-36769