This article is a mirror article of machine translation, please click here to jump to the original article.

View: 2964|Reply: 0

[Source] ASP.NET Core (twenty-five) dependencies inject Lazy lazy lazy initialization

[Copy link]
Posted on 10/10/2023 9:14:31 PM | | | |
Requirements: Add services ASP.NET Core, inject services through constructors, and want to delay initialize the implementation class (different logical processing according to the HTTP context request information), and think of using Lazy<T> for lazy for lazy initialization.

Review:

How Lazy in C# keeps threads safe
https://www.itsvse.com/thread-10621-1-1.html

C# performance optimization: Lazy initializes lazy with <T>a delay
https://www.itsvse.com/thread-7700-1-1.html
Inject directly into the interface

The constructor is injected directly into the interface service, and the code is as follows:

The execution order is as follows:



You can see the following execution order: IA implementation class -> HomeController console -> index method

Initialize with Lazy delay

If the controller constructor changes IA to Lazy<IA>, the error will look like this:

InvalidOperationException: Unable to resolve service for type 'System.Lazy`1[WebApplication6.IA]' while attempting to activate 'WebApplication6.Controllers.HomeController'.
The error is due to the fact that we have not registered for Lazy-related services, we need to register a Lazy<> generic service, the code is as follows:

Add to Service:

The execution order is as follows:



You can see the execution order: HomeController console -> Index method -> IA implementation class, you can see itIA interface delay initializationwill instantiate the IA implementation object when called.

(End)





Previous:CIDR: Read the CIDR address description in one article
Next:The front-end stores the localForage package of IndexedDB
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com