Requirements: In ASP.NET Core, we usually use AddTransient, AddScoped, and AddSingleton to register services with different life cycles according to our own business, if the project needs to register 100 services (database access layer, regular object naming rules), we need to write 100 lines of code to register, how to register these services dynamically or using reflection?
Through dynamic reflection, we only need a few lines of code to complete, and when we create a new service (because it will be scanned for new services when it is dynamically registered), we don't need to register it.
The dynamic registration service principle is to call builder. Services.AddServiceDescriptorway.
Our database access layer, interface name: IClassificationService, the object name of the implementation interface: ClassificationService, the database access layer name is followed by "Service", you can register all the database access layer services through this rule, the code is as follows:
IClassificationService interface code:
ClassificationService code:
(End)
|