Skip to content

Commit

Permalink
Update Dependency-Injection.md
Browse files Browse the repository at this point in the history
  • Loading branch information
EngincanV committed Jan 22, 2024
1 parent c4cde81 commit 0e0c461
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions docs/en/Dependency-Injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<ITaxCalculator>("taxCalculator")]
Expand All @@ -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<ITaxCalculator>("taxCalculator");
var calculator = ServiceProvider.GetRequiredKeyedService<ICalculator>("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<ITaxCalculator>("taxCalculator")]
Expand Down

0 comments on commit 0e0c461

Please sign in to comment.