Skip to content

Commit cffd8a7

Browse files
authored
Add example to correspond to text. Fixes #41220 (#41222)
1 parent ce38b87 commit cffd8a7

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

docs/core/extensions/dependency-injection.md

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Dependency injection
33
description: Learn how to use dependency injection within your .NET apps. Discover how to registration services, define service lifetimes, and express dependencies in C#.
44
author: IEvangelist
55
ms.author: dapine
6-
ms.date: 03/15/2024
6+
ms.date: 06/03/2024
77
ms.topic: overview
88
---
99

@@ -289,7 +289,19 @@ The framework provides service registration extension methods that are useful in
289289

290290
For more information on type disposal, see the [Disposal of services](dependency-injection-guidelines.md#disposal-of-services) section.
291291

292-
Registering a service with only an implementation type is equivalent to registering that service with the same implementation and service type. This is why multiple implementations of a service cannot be registered using the methods that don't take an explicit service type. These methods can register multiple *instances* of a service, but they will all have the same *implementation* type.
292+
Registering a service with only an implementation type is equivalent to registering that service with the same implementation and service type. For example, consider the following code:
293+
294+
```csharp
295+
services.AddSingleton<ExampleService>();
296+
```
297+
298+
This is equivalent to registering the service with both the service and implementation of the same types:
299+
300+
```csharp
301+
services.AddSingleton<ExampleService, ExampleService>();
302+
```
303+
304+
This equivalency is why multiple implementations of a service can't be registered using the methods that don't take an explicit service type. These methods can register multiple *instances* of a service, but they will all have the same *implementation* type.
293305

294306
Any of the above service registration methods can be used to register multiple service instances of the same service type. In the following example, `AddSingleton` is called twice with `IMessageWriter` as the service type. The second call to `AddSingleton` overrides the previous one when resolved as `IMessageWriter` and adds to the previous one when multiple services are resolved via `IEnumerable<IMessageWriter>`. Services appear in the order they were registered when resolved via `IEnumerable<{SERVICE}>`.
295307

0 commit comments

Comments
 (0)