From 0e0c4611ff9cf6a1156c69690b3fda4f7ffd514b Mon Sep 17 00:00:00 2001 From: Engincan VESKE <43685404+EngincanV@users.noreply.github.com> Date: Mon, 22 Jan 2024 11:03:48 +0300 Subject: [PATCH] Update Dependency-Injection.md --- docs/en/Dependency-Injection.md | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/en/Dependency-Injection.md b/docs/en/Dependency-Injection.md index 2d042a2b2a..58522c98cf 100644 --- a/docs/en/Dependency-Injection.md +++ b/docs/en/Dependency-Injection.md @@ -145,7 +145,7 @@ public class TaxCalculator : ITaxCalculator, ITransientDependency ### ExposeKeyedService Attribute -``ExposeKeyedServiceAttribute`` is used to control which keyed services are provided by the related class. Example: +`ExposeKeyedServiceAttribute` is used to control which keyed services are provided by the related class. Example: ````C# [ExposeKeyedService("taxCalculator")] @@ -155,14 +155,28 @@ public class TaxCalculator: ICalculator, ITaxCalculator, ICanCalculate, ITransie } ```` -``TaxCalculator`` class exposes ``ITaxCalculator`` interface with the key ``tax`` and ``ICalculator`` interface with the key ``calculator``. That means you can get keyed services from the ``IServiceProvider`` as shown below: +In the example above, the `TaxCalculator` class exposes the `ITaxCalculator` interface with the key `taxCalculator` and the `ICalculator` interface with the key `calculator`. That means you can get keyed services from the `IServiceProvider` as shown below: ````C# var taxCalculator = ServiceProvider.GetRequiredKeyedService("taxCalculator"); var calculator = ServiceProvider.GetRequiredKeyedService("calculator"); ```` -> Notice that the ``ExposeKeyedServiceAttribute`` is only expose keyed services. So, you can not inject ``ITaxCalculator`` or ``ICalculator`` in your application. If you want to expose both keyed and non-keyed services, you can use ``ExposeServicesAttribute`` and ``ExposeKeyedServiceAttribute`` together as shown below: +Also, you can use the [`FromKeyedServicesAttribute`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.fromkeyedservicesattribute?view=dotnet-plat-ext-8.0) to resolve a certain keyed service in the constructor: + +```csharp +public class MyClass +{ + //... + + public MyClass([FromKeyedServices("taxCalculator")] ITaxCalculator taxCalculator) + { + TaxCalculator = taxCalculator; + } +} +``` + +> Notice that the `ExposeKeyedServiceAttribute` only exposes the keyed services. So, you can not inject the `ITaxCalculator` or `ICalculator` interfaces in your application without using the `FromKeyedServicesAttribute` as shown in the example above. If you want to expose both keyed and non-keyed services, you can use the `ExposeServicesAttribute` and `ExposeKeyedServiceAttribute` attributes together as shown below: ````C# [ExposeKeyedService("taxCalculator")]