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. |