Skip to content

Commit a76a486

Browse files
authored
New dependency injection basics article (dotnet#41831)
* Add a new article for DI basics * Add to TOC * Cross reference. Fixes dotnet#41827 * Edit pass * Add run app details * Add missing bits * Add some xrefs * Correct xref
1 parent 441e452 commit a76a486

13 files changed

+275
-12
lines changed
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
---
2+
title: Dependency injection basics
3+
description: Learn how to use dependency injection (DI) in your .NET apps with this simple example. Follow along with this pragmatic guide to understand DI basics in C#.
4+
author: IEvangelist
5+
ms.author: dapine
6+
ms.date: 07/18/2024
7+
no-loc: [Transient, Scoped, Singleton, Example]
8+
---
9+
10+
# Understand dependency injection basics in .NET
11+
12+
In this article, you create a .NET console app that manually creates a <xref:Microsoft.Extensions.DependencyInjection.ServiceCollection> and corresponding <xref:Microsoft.Extensions.DependencyInjection.ServiceProvider>. You learn how to register services and resolve them using dependency injection (DI). This article uses the [Microsoft.Extensions.DependencyInjection](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection) NuGet package to demonstrate the basics of DI in .NET.
13+
14+
> [!NOTE]
15+
> This article doesn't take advantage of the [Generic Host](generic-host.md) features. For a more comprehensive guide, see [Use dependency injection in .NET](dependency-injection-usage.md).
16+
17+
## Get started
18+
19+
To get started, create a new .NET console application named **DI.Basics**. Some of the most common approaches for creating a console project are referenced in the following list:
20+
21+
- [Visual Studio: **File > New > Project**](/visualstudio/get-started/csharp/tutorial-console) menu.
22+
- [Visual Studio Code](https://code.visualstudio.com/) and the [C# Dev Kit extension's](https://code.visualstudio.com/docs/csharp/project-management): **Solution Explorer** menu option.
23+
- [.NET CLI: `dotnet new console`](/dotnet/core/tools/dotnet-new-sdk-templates#console) command in the terminal.
24+
25+
You need to add the package reference to the [Microsoft.Extensions.DependencyInjection](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection) in the project file. Regardless of the approach, ensure the project resembles the following XML of the _DI.Basics.csproj_ file:
26+
27+
:::code language="XML" source="snippets/di/di-basics/di-basics.csproj":::
28+
29+
## Dependency injection basics
30+
31+
Dependency injection is a design pattern that allows you to remove hard-coded dependencies and make your application more maintainable and testable. DI is a technique for achieving [Inversion of Control (IoC)](../../architecture/modern-web-apps-azure/architectural-principles.md#dependency-inversion) between classes and their dependencies.
32+
33+
The abstractions for DI in .NET are defined in the [Microsoft.Extensions.DependencyInjection.Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection.Abstractions) NuGet package:
34+
35+
- <xref:Microsoft.Extensions.DependencyInjection.IServiceCollection>: Defines a contract for a collection of service descriptors.
36+
- <xref:System.IServiceProvider>: Defines a mechanism for retrieving a service object.
37+
- <xref:Microsoft.Extensions.DependencyInjection.ServiceDescriptor>: Describes a service with its service type, implementation, and lifetime.
38+
39+
In .NET, DI is managed by adding services and configuring them in an `IServiceCollection`. After services are registered, as `IServiceProvider` instance is built by calling the <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider%2A> method. The `IServiceProvider` acts as a container of all the registered services, and it's used to resolve services.
40+
41+
## Create example services
42+
43+
Not all services are created equally. Some services require a new instance each time that the service container gets them (_transient_), while others should be shared across requests (_scoped_) or for the entire lifetime of the app (_singleton_). For more information on service lifetimes, see [Service lifetimes](dependency-injection.md#service-lifetimes).
44+
45+
Likewise, some services only expose a concrete type, while others are expressed as a contract between an interface and an implementation type. You create several variations of services to help demonstrate these concepts.
46+
47+
Create a new C# file named _IConsole.cs_ and add the following code:
48+
49+
:::code source="snippets/di/di-basics/IConsole.cs":::
50+
51+
This file defines an `IConsole` interface that exposes a single method, `WriteLine`. Next, create a new C# file named _DefaultConsole.cs_ and add the following code:
52+
53+
:::code source="snippets/di/di-basics/DefaultConsole.cs":::
54+
55+
The preceding code represents the default implementation of the `IConsole` interface. The `WriteLine` method conditionally writes to the console based on the `IsEnabled` property.
56+
57+
> [!TIP]
58+
> The naming of an implementation is a choice that your dev-team should agree on. The `Default` prefix is a common convention to indicate a _default_ implementation of an interface, but it's _not_ required.
59+
60+
Next, create an _IGreetingService.cs_ file and add the following C# code:
61+
62+
:::code source="snippets/di/di-basics/IGreetingService.cs":::
63+
64+
Then add a new C# file named _DeafultGreetingService.cs_ and add the following code:
65+
66+
:::code source="snippets/di/di-basics/DefaultGreetingService.cs":::
67+
68+
The preceding code represents the default implementation of the `IGreetingService` interface. The service implementation requires an `IConsole` as a primary constructor parameter. The `Greet` method:
69+
70+
- Creates a `greeting` given the `name`.
71+
- Calls the `WriteLine` method on the `IConsole` instance.
72+
- Returns the `greeting` to the caller.
73+
74+
The last service to create is the _FarewellService.cs_ file, add the following C# code before continuing:
75+
76+
:::code source="snippets/di/di-basics/FarewellService.cs":::
77+
78+
The `FarewellService` represents a concrete type, not an interface. It should be declared as `public` to make it accessible to consumers. Unlike other service implementation types that were declared as `internal` and `sealed`, this code demonstrates that not all services need to be interfaces. It also shows that service implementations can be `sealed` to prevent inheritance and `internal` to restrict access to the assembly.
79+
80+
## Update the `Program` class
81+
82+
Open the _Program.cs_ file and replace the existing code with the following C# code:
83+
84+
:::code source="snippets/di/di-basics/Program.cs":::
85+
86+
The preceding updated code demonstrates the how-to:
87+
88+
- Create a new `ServiceCollection` instance.
89+
- Register and configure services in the `ServiceCollection`:
90+
- The `IConsole` using the implementation factory overload, return a `DefaultConsole` type with the `IsEnabled` set to `true.
91+
- The `IGreetingService` is added with a corresponding implementation type of `DefaultGreetingService` type.
92+
- The `FarewellService` is added as a concrete type.
93+
- Build the `ServiceProvider` from the `ServiceCollection`.
94+
- Resolve the `IGreetingService` and `FarewellService` services.
95+
- Use the resolved services to greet and say goodbye to a person named `David`.
96+
97+
If you update the `IsEnabled` property of the `DefaultConsole` to `false`, the `Greet` and `SayGoodbye` methods omit writing to the resulting messages to console. A change like this, helps to demonstrate that the `IConsole` service is _injected_ into the `IGreetingService` and `FarewellService` services as a _dependency_ that influences that apps behavior.
98+
99+
All of these services are registered as singletons, although for this sample, it works identically if they were registered as _transient_ or _scoped_ services.
100+
101+
> [!IMPORTANT]
102+
> In this contrived example, the service lifetimes don't matter, but in a real-world application, you should carefully consider the lifetime of each service.
103+
104+
## Run the sample app
105+
106+
To run the sample app, either press <kbd>F5</kbd> in Visual Studio, Visual Studio Code, or run the `dotnet run` command in the terminal. When the app completes, you should see the following output:
107+
108+
```console
109+
Hello, David!
110+
Goodbye, David!
111+
```
112+
113+
### Service descriptors
114+
115+
The most commonly used APIs for adding services to the `ServiceCollection` are lifetime-named generic extension methods, such as:
116+
117+
- `AddSingleton<TService>`
118+
- `AddTransient<TService>`
119+
- `AddScoped<TService>`
120+
121+
These methods are convenience methods that create a <xref:Microsoft.Extensions.DependencyInjection.ServiceDescriptor> instance and add it to the `ServiceCollection`. The `ServiceDescriptor` is a simple class that describes a service with its service type, implementation type, and lifetime. It can also desribe implementation factories and instances.
122+
123+
For each of the services that you registered in the `ServiceCollection`, you could instead call the `Add` method with a `ServiceDescriptor` instance directly. Consider the following examples:
124+
125+
:::code source="snippets/di/di-basics/Program.ServiceDescriptors.cs" id="console":::
126+
127+
The preceding code is equivalent to how the `IConsole` service was registered in the `ServiceCollection`. The `Add` method is used to add a `ServiceDescriptor` instance that describes the `IConsole` service. The static method `ServiceDescriptor.Describe` delegates to various `ServiceDescriptor` constructors. Consider the equivalent code for the `IGreetingService` service:
128+
129+
:::code source="snippets/di/di-basics/Program.ServiceDescriptors.cs" id="greeting":::
130+
131+
The preceding code describes the `IGreetingService` service with its service type, implementation type, and lifetime. Finally, consider the equivalent code for the `FarewellService` service:
132+
133+
:::code source="snippets/di/di-basics/Program.ServiceDescriptors.cs" id="farewell":::
134+
135+
The preceding code describes the concrete `FarewellService` type as both the service and implementation types. The service is registered as a singleton service.
136+
137+
## See also
138+
139+
- [.NET dependency injection](dependency-injection.md)
140+
- [Dependency injection guidelines](dependency-injection-guidelines.md)
141+
- [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)

docs/core/extensions/dependency-injection-guidelines.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Dependency injection guidelines
33
description: Discover effective dependency injection guidelines and best practices for developing .NET apps. Deepen your understanding of inversion of control.
44
author: IEvangelist
55
ms.author: dapine
6-
ms.date: 02/28/2024
6+
ms.date: 07/18/2024
77
ms.topic: conceptual
88
---
99

@@ -214,4 +214,5 @@ In the preceding code, `Bar` is retrieved within an <xref:Microsoft.Extensions.D
214214
## See also
215215

216216
- [Dependency injection in .NET](dependency-injection.md)
217+
- [Understand dependency injection basics in .NET](dependency-injection-basics.md)
217218
- [Tutorial: Use dependency injection in .NET](dependency-injection-usage.md)

docs/core/extensions/dependency-injection-usage.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Use dependency injection
33
description: Learn how to use dependency injection in your .NET apps with this comprehensive tutorial. Follow along with this pragmatic guide to understand DI in C#.
44
author: IEvangelist
55
ms.author: dapine
6-
ms.date: 07/08/2024
6+
ms.date: 07/18/2024
77
ms.topic: tutorial
88
no-loc: [Transient, Scoped, Singleton, Example]
99
---
@@ -126,5 +126,6 @@ From the app output, you can see that:
126126

127127
## See also
128128

129-
* [Dependency injection guidelines](dependency-injection-guidelines.md)
130-
* [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
129+
- [Dependency injection guidelines](dependency-injection-guidelines.md)
130+
- [Understand dependency injection basics in .NET](dependency-injection-basics.md)
131+
- [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)

docs/core/extensions/dependency-injection.md

Lines changed: 5 additions & 8 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: 06/03/2024
6+
ms.date: 07/18/2024
77
ms.topic: overview
88
---
99

@@ -110,18 +110,14 @@ With dependency injection terminology, a service:
110110
The framework provides a robust logging system. The `IMessageWriter` implementations shown in the preceding examples were written to demonstrate basic DI, not to implement logging. Most apps shouldn't need to write loggers. The following code demonstrates using the default logging, which only requires the `Worker` to be registered as a hosted service <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionHostedServiceExtensions.AddHostedService%2A>:
111111

112112
```csharp
113-
public class Worker : BackgroundService
113+
public sealed class Worker(ILogger<Worker> logger) : BackgroundService
114114
{
115-
private readonly ILogger<Worker> _logger;
116-
117-
public Worker(ILogger<Worker> logger) =>
118-
_logger = logger;
119-
120115
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
121116
{
122117
while (!stoppingToken.IsCancellationRequested)
123118
{
124-
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
119+
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
120+
125121
await Task.Delay(1_000, stoppingToken);
126122
}
127123
}
@@ -450,6 +446,7 @@ public class ExampleService
450446

451447
## See also
452448

449+
- [Understand dependency injection basics in .NET](dependency-injection-basics.md)
453450
- [Use dependency injection in .NET](dependency-injection-usage.md)
454451
- [Dependency injection guidelines](dependency-injection-guidelines.md)
455452
- [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
internal sealed class DefaultConsole : IConsole
2+
{
3+
public bool IsEnabled { get; set; } = true;
4+
5+
void IConsole.WriteLine(string message)
6+
{
7+
if (IsEnabled is false)
8+
{
9+
return;
10+
}
11+
12+
Console.WriteLine(message);
13+
}
14+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
internal sealed class DefaultGreetingService(
2+
IConsole console) : IGreetingService
3+
{
4+
public string Greet(string name)
5+
{
6+
var greeting = $"Hello, {name}!";
7+
8+
console.WriteLine(greeting);
9+
10+
return greeting;
11+
}
12+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public class FarewellService(IConsole console)
2+
{
3+
public string SayGoodbye(string name)
4+
{
5+
var farewell = $"Goodbye, {name}!";
6+
7+
console.WriteLine(farewell);
8+
9+
return farewell;
10+
}
11+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
public interface IConsole
2+
{
3+
void WriteLine(string message);
4+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
public interface IGreetingService
2+
{
3+
string Greet(string name);
4+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using Microsoft.Extensions.DependencyInjection;
2+
3+
internal partial class Program
4+
{
5+
internal static void AddConsole(IServiceCollection services)
6+
{
7+
// <console>
8+
services.Add(ServiceDescriptor.Describe(
9+
serviceType: typeof(IConsole),
10+
implementationFactory: static _ => new DefaultConsole
11+
{
12+
IsEnabled = true
13+
},
14+
lifetime: ServiceLifetime.Singleton));
15+
// </console>
16+
}
17+
18+
public static void AddGreetingService(IServiceCollection services)
19+
{
20+
// <greeting>
21+
services.Add(ServiceDescriptor.Describe(
22+
serviceType: typeof(IGreetingService),
23+
implementationType: typeof(DefaultGreetingService),
24+
lifetime: ServiceLifetime.Singleton));
25+
// </greeting>
26+
}
27+
28+
public static void AddFarewellService(IServiceCollection services)
29+
{
30+
// <farewell>
31+
services.Add(ServiceDescriptor.Describe(
32+
serviceType: typeof(FarewellService),
33+
implementationType: typeof(FarewellService),
34+
lifetime: ServiceLifetime.Singleton));
35+
// </farewell>
36+
}
37+
}

0 commit comments

Comments
 (0)