[Preparations for interview] 3. What is dependency injection ?,

Source: Internet
Author: User

[Preparations for interview] 3. What is dependency injection ?,

Before talking about dependency injection, you should first understand what interfaces are.

We all know the interface rules when learning programming: (Source: Baidu encyclopedia)

  • 1. The interface is a reference type, and multiple inheritance can be implemented through the interface.
  • The interface members in 2.c # cannot have modifiers such as new, public, protected, internal, and private.
  • 3. only "abstract" members can be declared in the interface (so the interface cannot be instantiated directly next (that is, the instance object of an interface cannot be declared using the new operator )), you cannot declare a shared domain or private member variable.
  • 4. The interface declaration does not include data members. It can only contain methods, attributes, events, indexes, and other Members.
  • 5. The interface name generally uses "I" as the first letter (of course it can be declared without such a statement), which is also one of the differences between interfaces and classes.
  • 6. The access level of interface members is the default value (the default value is public). Therefore, you cannot specify any access modifiers for interface members during declaration. Otherwise, the compiler reports an error.
  • 7. The interface members cannot have static, abstract, override, and virtual modifiers. If you use the new modifier, no error is reported, but a warning is given 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 to say, you only need to specify the name and parameter of the interface member when declaring the interface.
  • 9. Once an interface is implemented, the implementation class must implement all the members of the interface, unless the implementation class itself is an abstract class (using specific executable code to implement operations on the abstract members of the interface ).

So many concepts are often seen in the fog. The Interface Usage in the project is also based on the old code. If it is a self-developed code or demo, there is no interface to use. (The excuse for myself is that I just want to do something small and can run smoothly without using interfaces .)

 

What is an interface? (My own understanding is not necessarily true)

The interface is prepared to replace an implementation that may be outdated or incorrect. Just think about our computer, and there are interfaces everywhere. Usb, memory stick, hard disk, battery, keyboard... and so on all have their own interfaces. We can change a larger hard disk or a faster solid state disk through the hard disk interface. If the keyboard breaks down, you can also use the keyboard interface to buy a new keyboard. This is the obvious benefit of the interface. The interface can also be understood as a convention of the big family. Specifies the size function of a specific interface.

 

The same is true for writing code. In some cases, the Code may change frequently, and the interface conventions are used in scenarios where the logic is often modified. Next we will use the hard disk interface for example.

First, define a hard disk interface. (A name attribute, a method for reading and writing)

/// <Summary> /// hard disk interface /// </summary> interface IHardDisk {/// <summary> /// hard disk name attribute /// </summary> string name {get ;} /// <summary> /// Method for reading data /// </summary> void read (); /// <summary> /// write data /// </summary> void write (string str );}

Then we bought a GB hard disk, which implemented the above interface.

Public class HardDisk200: IHardDisk {public string name {get {return "200200200200" ;}} public void read () {Console. writeLine ("I can write data .... ");} public void write (string str) {Console. writeLine (str );}}

Use this hard disk on your computer.

Static void Main (string [] args) {// here, h is a device inserted in the interface IHardDisk h = new HardDisk200 (); h. read (); h. write (h. name + ", I can write data"); Console. readKey ();}

 

One day, we found that this hard disk was too small and needed to be changed to 1 TB. (So we can store a lot of movies >_<), so buy it.

Public class HardDisk1T: IHardDisk {public string name {get {return "I Am a 1 TB hard drive" ;}} public void read () {Console. writeLine ("I can write data .... ");} public void write (string str) {Console. writeLine (str );}}

How can I use it? As long as the interface on the computer is directly inserted into the new hard disk is OK, other places do not need to change.

It must be stored or stored, that is, it must be able to write and read data .)

 

After learning about what interfaces are, let's talk about the main theme of today.

Let's start with the example first, and it's an example that we have learned programming, three layers. (What? What is Layer 3? You can skip it. you can skip the tutorial first)

Let's first write a simple layer-3 pseudo code.

DAL:

Public class DALMsSqlHelper {public int add (string str) {//... omitted specific implementation return 1;} //... omitted specific implementation, such as modification and deletion query}

BLL:

Public class BLLAddStudent {DALMsSqlHelper mssql = null; public BLLAddStudent () {mssql = new DALMsSqlHelper ();} public int addStudent () {string str = "";//... the specific implementation of return mssql is omitted. add (str );}}

UI:

 public class UI {     BLLAddStudent s = new BLLAddStudent();     public UI()     {         s.addStudent();     } }

It should be said that the simplicity should not be on the Simple Layer 3.

Just a year after the system was used, the boss said: "I heard that oracle is awesome, and big companies use oracle. Let's change it. ". Okay, let's change it.

DAL:

Public class DALOracleSqlHelper {public int addOracle (string str) {//... omitted specific implementation return 1;} //... omitted specific implementation, such as modification and deletion query}

Obviously, BLL also needs to be modified because BLL references the DAL Query Class.

BLL:

Public class BLLAddStudent {DALOracleSqlHelper mssql = null; public BLLAddStudent () {mssql = new DALOracleSqlHelper ();} public int addStudent () {string str = "";//... the specific implementation of return mssql is omitted. addOracle (str );}}

Don't you change the database? Why is the change so big? What if my boss needs to switch back to oracle one day? You have to find a solution.

First, we define an interface for data access.

public interface ISqlHelper{    int add();
//... Omitting the specific implementation, such as modifying the deletion Query
 }

Modify BAL as follows:

Public class DALMsSqlHelper: ISqlHelper {public int add (string str ){//... omit the specific implementation of return 1 ;}//... omitted specific implementation, such as modifying and deleting the query} public class DALOracleSqlHelper: ISqlHelper {public int addOracle (string str ){//... omit the specific implementation of return 1 ;}//... omit the specific implementation, such as modifying and deleting the public int add (string str ){//... omitted specific implementation return 1 ;}}

BLL:

Public class BLLAddStudent {ISqlHelper mssql = null; public BLLAddStudent (ISqlHelper sqlhelper) {mssql = sqlhelper;} public int addStudent () {string str = "";//... the specific implementation of return mssql is omitted. add (str );}}

UI:

public class UI{           public UI()    {        ISqlHelper sqlhelper = new DALOracleSqlHelper();        BLLAddStudent s = new BLLAddStudent(sqlhelper);        s.addStudent();    }}

What if the boss wants to change to mssql. You only need to modify the UI

 

Another year later, because of the company's slump. So I came to the demand again. Boss: "Alas, forget it. Let's use mysql. Free of charge, saving the company ". So we have to modify it again.

First, you need to write a new mysql implementation.

DAL:

Public class DALMySqlHelper: ISqlHelper {public int add (string str) {//... omitted specific implementation return 1;} //... omitted specific implementation, such as modification and deletion query}

The UI is implemented as follows:

public class UI{           public UI()    {        ISqlHelper sqlhelper = new DALMySqlHelper();        BLLAddStudent s = new BLLAddStudent(sqlhelper);        s.addStudent();    }}

Have we found anything. We just added a mysql implementation in DAL and modified the interface structure at the UI Layer. Among them, BLL is not moved at all.

Yes, so we can say that the UI here is "dependency injection" for BLL, and BLL is "control inversion" for UI. Therefore, I think dependency injection and control reversal are the same concept, but they have different positions.

 

As shown above, even though the BLL layer does not need to change, you can add a new data source for access. So can we not modify the UI Layer?

Here we can use the reflection mentioned in the previous article.

 

Then, no matter what the boss wants, I just need to modify the configuration file. No code is required. (If you want to add a new data source, you only need to implement it again and then modify the configuration file ).

 

I think this example is very inappropriate, but I did not expect any good examples. This is the first time. If you can see it, it is the best. If you cannot understand it, find more information.

Next we will continue to write the front-end stuff. (Because the new job has been found and Html5 and Css3 need to be used. Take the opportunity to find an excuse to learn the front-end.> _ <)

In the future, I still want to finish writing this series.

Link: http://www.cnblogs.com/zhaopei/p/5078539.html

 

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.