[Consolidating C #] Iii. What is dependency injection?

Source: Internet
Author: User
Tags mssql

Interface

Before you say dependency injection, let's understand what the interface is.

When we are learning programming, we know that the relevant rules of interface: (Source Baidu Encyclopedia)

    • 1. An interface is a reference type, and multiple inheritance can be achieved through an interface.
    • 2. Members of interfaces in C # cannot have new, public, protected, internal, private, and other modifiers.
    • 3. An "abstract" member can only be declared in an interface (so the interface cannot be instantiated directly next (that is, an instance object of an interface cannot be declared using the new operator)), and cannot declare a common domain or a private member variable.
    • 4. The interface declaration does not include data members, only methods, properties, events, indexes, and so on.
    • 5. The interface name is usually "I" as the first letter (of course, not such a declaration can also), which is also one of the differences between the interface and the class.
    • 6. The access level of the interface member is default (public by default), so no access modifiers can be specified for the interface member at the time of declaration, or the compiler will give an error.
    • 7. Interface members cannot have static, abstract, override, virtual modifiers, use the new modifier without error, but give a warning that no keyword new is required.
    • 8. When declaring an interface member, you are not allowed to write specific executable code for the interface member, that is, as long as the interface's member names and parameters are indicated when the interfaces are declared.
    • 9. Once the interface is implemented, the implementation class must implement all the members of the interface, unless the implementation class itself is an abstract class (an operation that implements an abstract member of an interface through concrete executable code).

Many times it is foggy to see so many concepts. The interface used in the project is also under the old code according to gourd painting scoop. If it is your own practiced hand code or demo, it is not using the interface. The excuse is, I just do small things, do not need to use the same interface can run very much. )

What is an interface? (Say my own understanding, not necessarily right)

The interface is intended to replace a possible outdated or erroneous implementation. Just think of our computer, it is all over the interface. USB, Memory stick, hard disk, battery, keyboard ... And so on, all have their own interfaces. We can switch to a larger hard drive via the hard drive interface or a faster SSD. If the keyboard is broken, you can also buy a new keyboard through the keyboard interface to change. This is the obvious benefit of the interface. Interface can also be understood as the agreement of everyone. The size function of a particular interface is contracted, and so on.

Then we write code the same, in some places may change frequently, the logic will often modify the place to use the interface convention. Let's use the hard drive interface to do the example.

First define a hard disk interface. (a Name property, a method of reading a write)

<summary>///hard Drive interface///</summary>interface iharddisk{///<summary>//    HDD name attributes//    </summary>    string name {get;}    <summary>    ////Read Data method///</summary> void Read ();    <summary>    ///write Data    ///</summary> void Write (String str);}

Then we bought a 200G hard drive, which implements the above interface.

public class harddisk200:iharddisk{Public    string name    {        get        {            return "I am 200G hdd";        }    } public    void Read ()    {        Console.WriteLine ("I can write data oh ....");    }    public void Write (string str)    {        Console.WriteLine (str);    }}

Use this hard drive in your computer.

static void Main (string[] args) {    //the H here is a device plugged into the interface    iharddisk h = new HardDisk200 ();    H.read ();    H.write (H.name + ", I can write data Oh");    Console.readkey ();}

One day, we found this hard drive is too small, need to change a 1T. (So we can save a lot of movies >_<), then buy it.

public class harddisk1t:iharddisk{Public    string name    {        get        {            return "I am 1T hdd";        }    } Public     Void Read ()    {        Console.WriteLine ("I can write data oh ....");    }     public void Write (string str)    {        Console.WriteLine (str);    }}

And then how to use it? As long as the interface on the computer directly plug in the new hard disk is OK, and other places do not have to change.

This is the benefit of using interfaces. When we find that the computer is too slow one day, we can buy a solid-state drive, directly in the interface to use the place to change, and other places do not have to modify at all.

This allows us to flexibly replace any object that implements the interface at different times or under different circumstances without modifying the code elsewhere.

Or, the device that implements this interface is the storage device. (It must be stored and stored, which means that data can be written and read.) )

Dependency Injection

Now that we know what the interface is, let's go on to the main topic today.

Let's start with examples, and we've learned the examples of programming that we know, three layers. What You don't know what the three floor is? Then you don't look, you have to cram before you come back.

Let's start by writing a simple three-layer pseudo-code.

DAL:

public class Dalmssqlhelper {public     int Add (string str)     {         //... Omit the concrete implementation of         return 1;     }     //... Omit a specific implementation, such as modifying a delete query}

Bll:

public class blladdstudent{    dalmssqlhelper mssql = NULL;    Public blladdstudent ()    {        mssql = new Dalmssqlhelper ();    }    public int addstudent ()    {        string str = "";  //... Omit the concrete implementation of        return Mssql.add (str);}    }

Ui:

public class UI {     blladdstudent s = new blladdstudent ();     Public UI ()     {         s.addstudent ();     }}

It should be said simply cannot be in the simple three-storey.

After a year in the system, the boss said: "I heard Oracle is very good, big companies are using Oracle." Let's change it, too. “。 OK, let's change it.

DAL:

public class daloraclesqlhelper{Public    int addoracle (string str)    {        //... Omit the concrete implementation of        return 1;    }    //... Omit a specific implementation, such as modifying a delete query}

Obviously the BLL is also going to be modified because the BLL references the Dal's query class.

Bll:

public class blladdstudent{    daloraclesqlhelper mssql = NULL;    Public blladdstudent ()    {        mssql = new Daloraclesqlhelper ();    }    public int addstudent ()    {        string str = "";  //... Omit the concrete implementation of        return mssql.addoracle (str);}    }

No, just a different database? Why should the boss change back to Oracle someday if it changes so much? This has to be a good idea.

First, we define an interface for data access.

public interface isqlhelper{    int add ();
    //... Omit specific implementations, such as modifying a delete query
}

The DAL is modified as follows:

public class dalmssqlhelper:isqlhelper{Public    int Add (string str)    {        //... Omit the concrete implementation of        return 1;    }    //... Omit specific implementations, such as modifying a delete query}public class daloraclesqlhelper:isqlhelper{public    int addoracle (string str)    {        //... Omit the concrete implementation of        return 1;    }    //... Omit specific implementations, such as modify delete query public    int Add (string str)    {        //... Omit the concrete implementation of        return 1;    }}

Bll:

public class Blladdstudent {     isqlhelper mssql = NULL;     Public blladdstudent (Isqlhelper sqlhelper)     {         mssql = SqlHelper;     }     public int addstudent ()     {         string str = "";  //... Omit the concrete implementation of         return Mssql.add (str);}     }

Ui:

public class ui{public           UI ()    {        Isqlhelper sqlhelper = new Daloraclesqlhelper ();        blladdstudent s = new blladdstudent (sqlhelper);        S.addstudent ();    }}

If one day the boss will change what MSSQL do. So just modify the UI

Another year later, because of the company's slump. So the demand has come again. Boss: "Oh, forget it." Let's still use MySQL. Free, save a little for the company. " So we're going to have to change it again.

First you need to re-write the MySQL implementation.

DAL:

public class dalmysqlhelper:isqlhelper{Public    int Add (string str)    {        //... Omit the concrete implementation of        return 1;    }    //... Omit a specific implementation, such as modifying a delete query}

The UI is implemented as follows:

public class ui{public           UI ()    {        Isqlhelper sqlhelper = new Dalmysqlhelper ();        blladdstudent s = new blladdstudent (sqlhelper);        S.addstudent ();    }}

We have not found. We just added a MySQL implementation in the Dal and modified the interface constructs under the UI layer. The BLL we didn't move it at all.

Yes, so we can say that the UI here is "dependency injection" for the BLL, and the BLL is "inversion of control" for the UI. So, I feel that dependency injection and control reversal are the same concept, just different positions.

Above, we see that although the BLL layer has no need to change, it can add access to a data source. So can we also not modify the UI layer?

Here we can use the reflection of our last speech.

Then, no matter how the boss wants to toss, I just need to change the configuration file. You don't even have to move the code. (If you need to add a new data source operation, just re-implement it, and then change the configuration file).

[Consolidating C #] Iii. What is dependency injection?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.