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

View: 253|Reply: 0

[ASP.NET] ASP.NET Core (32) depends on injecting KeyedServices key services

[Copy link]
Posted on 2025-10-11 11:15:07 | | | |
What is KeyedServices?

Dependency injection (DI) is ubiquitous in ASP.NET Core. You can use it for custom services, but more importantly, the framework itself always uses DI as well. Most of what you can configure in ASP.NET Core is configured through DI.

For keyed services, another piece of information is stored in the ServiceDescriptor, which is the ServiceKey used to identify the service. The key can be any object, but usually string or enum (can be constants, so it can be used in properties). For non-keyed services, identity registration; For keying services, the combined identity registration with ServiceType is registered. ServiceTypeServiceKey。

A keying service refers to a mechanism that uses keys to register and retrieve dependency injection (DI) services. Register a service by calling AddKeyedSingleton (or AddKeyedScoped or AddKeyedTransient), associated with a key. Use the [FromKeyedServices] property to specify the key to access the registered service.

  • AddKeyedScoped
  • AddKeyedSingleton
  • AddKeyedTransient

KeyedServices testing

Create a new interface to send notifications, implement email, SMS, and message push methods, register through the key service, and call its specific implementation by specifying the service ID, the code is as follows:
Execute as shown below:



Injecting code via a constructor is as follows:

Reference:
The hyperlink login is visible.
The hyperlink login is visible.




Previous:OneKey Pro cryptocurrency hardware wallet purchase tutorial
Next:Linux servers cut nginx logs based on logrotate
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