How does one understand control inversion in asp.net?
IOC is interpreted as: "Inversion of control is a common characteristic of frameworks, so saying that these lightweight containers are special because they use inversion of control is like saying my car is special because it has wheels."
I want to explain this concept one by one to facilitate my understanding. Control reversal, literally, means that control changes from passive to active, or passive to passive. From this perspective, IOC becomes very easy to understand.
For example, if your supervisor asks you to do one thing, there are so many processes and the supervisor instructs you to do things (at this time, the initiative is in charge, and you are passive)
You receive commands to do things (at this time, the theme is you, you are active, and control is in your hands) You complete things (at this time, the theme is still you, and control is in your hands)
Report the supervisor to finish the task (the initiative is handed over to the supervisor)
The entire process above completes IOC once. From the above, we can see that the basic idea of IOC is the conversion process of control.
Example of code:
If there is Class A and Class B, inside A, a B will be initialized to call A essentials of B.
DoMethod public Class B
{
Public void DoMethod ()
{
/// Do somthing;
}
}
Public Class
{
Public void Excute ()
{
B B = new B ();
B. DoMethod ();
}
}
Run the following command in the Main function: A a = new A (); a. Excute ();
From the two lines of code, there is actually an IOC process. a --> B --> a, the key point of understanding is that when A calls Excute internally, B. doMethod execution. After understanding IOC, let's look at DI again. We can see from the above that when A calls B, we can see that a B must also be instantiated when an instance of A is initialized, that is to say, if there is no question about B or B, A cannot be instantiated. This produces A dependency, that is, A depends on B. This dependency is coupling from the design perspective, obviously, it cannot meet the requirements of high cohesion and low coupling. At this time, decoupling is required. Of course, there are many essentials for decoupling, and DI is one of them. No matter what kind of decoupling essentials, it doesn't mean that A and B are completely unrelated, but that the implementation of this kind of association is concealed, not so direct, but easy to implement and easy to expand, unlike the code above, a new B is provided directly. Why do we always associate IOC with DI? It is because the basic idea of DI is IOC, and the essentials of reflecting IOC is Service Locator, which seems to involve very little. In fact, these are derived from java. Although I have not used java for several years, Spring will use IOC and DI as if they are closely connected.