The simple to understand what’s Dependency Injection

1. Tom and his hobbies

Tom has 3 hobbies, there are playing games, watching Youtube, and photography with a mobile phone. So we can use a simple codes for that:

public class Tom : Person
{
    private string _name;
    private int _age;

    public void PlayGames() 
    {
        //play games
    } 

    public void WatchYoutube()
    {
        //watch Youtube
    }

    public void Photography()
    {
        //photography
    }
}

but as a person, Tom can’t do the above by himself, he must be used a phone! So he bought an iPhone8(maybe a few years ago :laughing:), and then we update the codes

Do you want to be a good trading in cTrader?   >> TRY IT! <<
public class iPhone8 : iPhone
{
    public void PlayGames(string user="somebody") 
    {
        Console.WriteLine(user + " is playing Games");
    } 

    public void WatchYoutube(string user="somebody")
    {
        Console.WriteLine(user + " is watching Youtube");
    }

    public void Photography(string user="somebody")
    {
        Console.WriteLine(user + " is photography");  
    }
}

Tom cherishes his new mobile phone very much and firmly controls it every day, so Tom become as below

public class Tom : Person
{
    private string _name;
    private int _age;

    public Tom()
    {
        this._name = "Tom";
        this._age = 25;
    }

    public void PlayGames() 
    {
        //...omit some codes
        var phone = new iPhone8();
        phone.PlayGames(this._name);
    } 

    public void WatchYoutube()
    {
        //...omit some codes
        var phone = new iPhone8();
        phone.WatchYoutube(this._name);
    }

    public void Photography()
    {
        //...omit some codes
        var phone = new iPhone8();
        phone.Photography(this._name);
    }
}

Today is Sunday, Tom day off at home and he get up to play the phone

var tom = new Tom(); //get up
tom.PlayGames();
tom.WatchYoutube();
tom.Photography();

and we can see the result in console

Tom is playing Games
Tom is watching Youtube
Tom is photography

2. Tom’s Happiness and Sadness

Tom and his mobile phone once spent a good time together. Whenever he had free time, he would hold his mobile phone, play games, watch youtube, and photography. He felt that he didn’t need a girlfriend at all, as long as he had a mobile phone. That’s enough! 🙂

But who would have thought that the repeated system updates completely shattered his dreams, his mobile phone became more and more stuck, and the battery life became shorter and shorter, until one day in the cold wind, his The phone finally couldn’t stand the cold, and turned off without looking back.

Tom was very sad. He realized that he had to change his mobile phone. :worried:

In order to get a better user experience, Tom gritted his teeth and bought an iphone14. This mobile phone has a loud ringtone, a lot of power, and dual card dual standby. Tom likes it very much, but he encountered a problem, which is He depend too much on the original iPhone 8 before, and they have been deeply coupled together. If he wants to change his mobile phone, he has to pick up a knife to transform himself, and replace all the iphone 8 in his body with the iphone 14.

After a long transformation process, Tom finally replaced all iphone 8 in the code with iphone 14. Although it is very hard, Tom thinks he is happy.

So Tom happily took his mobile phone to work, and was stolen by a thief on the way back. In order to make an emergency, Tom had to reuse the iPhone 8 that had just been abandoned, but when he thought of the long transformation process, Tom felt unspeakable grievances in his heart. He felt that he was too dependent on the mobile phone. To reinvent himself, it’s not just over coupling, it’s putting the cart before the horse, and he’s yelling to the sky, I’m not going to control my phone anymore!

The creator in the sky, that is, I am a programmer, heard his cry, and I told him, you don’t need to control your mobile phone anymore, let me manage it, and give me the control. This is called Inversion Of Control.

3. The wisdom of the creator

Hearing my words, Tom was both happy and a little scared. He knelt down and kowtowed a few times, and said reverently: “So you are the legendary Creator, God Bagmaker. I heard you just said The words of Inversion Of Control means that I will hand over the control of the mobile phone to you from my hands, but this is just your idea, it is just a kind of thought, what method should be used to achieve Inversion Of Control, and let me know how about continuing to use the phone?”

“Heh”, as the Creator, after showing my disdain, I dropped the characters, “Dependency Injection!”

Next, the great me began to inhumanely transform Tom, as below

public class Tom : Person
{
    private string _name;
    private int _age;
    private iPhone _phone; //set the phone as the member for himself

    public Tom(phone)
    {
        this._name = "Tom";
        this._age = 25;
        this._phone = phone;
        Console.WriteLine("Tom is weak up!");
    }

    public void PlayGames() 
    {
        //...omit some codes
        this._phone.PlayGames(this._name);
    } 

    public void WatchYoutube()
    {
        //...omit some codes
        this._phone.WatchYoutube(this._name);
    }

    public void Photography()
    {
        //...omit some codes
        this._phone.Photography(this._name);
    }
}

Next, let’s simulate and run Tom’s day

//create the iPhone 14 instance
var phone = new iPhone14();
if(phone.isBroken()){
    //if iphone 14 is broken then use iphone 8
    phone = new iPhone8();
}
//Tom don't need to care about what kind of the mobile phone now
var tom = new Tom(phone);
tom.PlayGames();
tom.WatchYoutube();
tom.Photography();

We need to check whether the iPhone14 can be use, if not then change to iPhone8 and then weak up Tome, in other words, the mobile phone he dependent on is injected directly into him, he doesn’t need to care what mobile phone he is holding, he just needs to use it directly, and this is the Dependency Injection !

3. Tom’s Perception

Tom’s life began to become simpler, and he used the time he saved to write notes. He wrote in his notebook as below:

I used to have a strong desire for control, and I relied too much on my mobile phone, which led to a high degree of coupling between me and the mobile phone. As long as there is a slight problem with the mobile phone, I have to transform myself. This is a waste of time and easy to fail.

Since I handed over the control to the Creator, he has already selected a mobile phone for me before waking me up every day. I just need to play with the mobile phone as usual, and I don’t need to care about the mobile phone at all. Even if there is a problem with the mobile phone, it can be fixed directly by the Creator, and there is no need to reinvent myself.

I have bought seven mobile phones and handed them over to the Creator. I change one every day, and I am very happy!

I also got this insight from it:

If the function realization of a class A needs the help of class B, then class B is said to be a dependency of class A. If class B is instantiated inside class A, then the relationship between the two classes will be a high coupling. Once there is a problem with class B, class A also needs to be transformed.

If there are many such cases and there are many dependencies between each class, then there will be a situation that affects the whole body. In this case, the program will be extremely difficult to maintain and easy to problems.

To solve this problem, it is necessary to extract the control of class A from class B and hand it over to a third party to do it, and invert the control to the third party, which is called inversion of control (IOC).

Inversion of control is an idea and a possible result that can solve problems, and dependency injection (DI) is its most typical implementation method. The third party (we call it the IOC Container) controls the dependency, and injects it into class A through methods such as constructors, properties, or factory patterns, thus decoupling class A and class B to a great extent! :smiley:

Loading

Views: 14
Total Views: 411 ,

One thought on “The simple to understand what’s Dependency Injection

Leave a Reply

Your email address will not be published. Required fields are marked *