In the new ASP.NET Core, a large number of dependency injections are used to write code.
For example, in our Startup class, we can see the following:
AddMvc AddDbContext includes the AddDirectoryBrowser we used for directory tours before:
They are all frameworks that provide good services, and we can use them directly by injecting them.
Inversion of Control (IoC) is a design principle in object-oriented programming that can be used to reduce the coupling between computer code. The most common method is called Dependency Injection (DI), and there is also a method called "Dependency Lookup". By controlling the inversion, when an object is created, an external entity that controls all objects in the system passes to it a reference to the object it depends on. It can also be said that dependencies are injected into the object. To use the ioc, the Startup class needs to reference Microsoft.Extensions.DependencyInjection(ps, which is already quite straightforward: Microsoft.. Expand... Dependency injection - - ,)
Inject the lifecycle of a service
Microsoft provides 3 life cycles for self-injected services.
Transient
An instantaneous lifecycle service that is created every time it is requested. This lifecycle is best suited for lightweight, stateless services.
Scoped
In the same scope, the service is created only once per request.
Singleton (Only)
The global is only created once, the first time it is requested, and then it is always used.
How do you use these three life cycles? We can use different methods directly when injecting, the code is as follows:
Let's test the specific generation of these three life cycles
We write three interfaces with different names and 3 different classes to implement the interfaces, as follows:
In each implementation class's constructor, we generate a new GUID, which allows us to determine whether the class has re-executed the constructor.
Inject services into the controller
There are generally three ways of injection: constructor injection, method injection, and attribute injection. Microsoft's own IOC container uses constructor injection by default (Attribute injection is not supported, but it can be achieved with a third-party container replacement)
View page code:
Run the project and access it through 2 different browsers, as shown below:
We found that the GUIDs generated twice in the instantaneous life cycle are inconsistent, indicating that the object is not the same.
However, the scope lifecycle is the same, because under the same scope, the GUID of the service used twice in the same browser is the same, indicating that the same object is used.
In the case of a singleton, two different browsers access always the same GUID, indicating that the same object is being called.
(End)
|