Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New dependency injection basics article #41831

Merged
merged 8 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions docs/core/extensions/dependency-injection-basics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
---
title: Dependency injection basics
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#.
author: IEvangelist
ms.author: dapine
ms.date: 07/18/2024
no-loc: [Transient, Scoped, Singleton, Example]
---

# Understand dependency injection basics in .NET

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.

> [!NOTE]
> 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).

## Get started

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:

- [Visual Studio: **File > New > Project**](/visualstudio/get-started/csharp/tutorial-console) menu.
- [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.
- [.NET CLI: `dotnet new console`](/dotnet/core/tools/dotnet-new-sdk-templates#console) command in the terminal.

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:

:::code language="XML" source="snippets/di/di-basics/di-basics.csproj":::

## Dependency injection basics

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.

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:

- <xref:Microsoft.Extensions.DependencyInjection.IServiceCollection>: Defines a contract for a collection of service descriptors.
- <xref:System.IServiceProvider>: Defines a mechanism for retrieving a service object.
- <xref:Microsoft.Extensions.DependencyInjection.ServiceDescriptor>: Describes a service with its service type, implementation, and lifetime.

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.

## Create example services

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

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.

Create a new C# file named _IConsole.cs_ and add the following code:

:::code source="snippets/di/di-basics/IConsole.cs":::

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:

:::code source="snippets/di/di-basics/DefaultConsole.cs":::

The preceding code represents the default implementation of the `IConsole` interface. The `WriteLine` method conditionally writes to the console based on the `IsEnabled` property.

> [!TIP]
> 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.

Next, create an _IGreetingService.cs_ file and add the following C# code:

:::code source="snippets/di/di-basics/IGreetingService.cs":::

Then add a new C# file named _DeafultGreetingService.cs_ and add the following code:

:::code source="snippets/di/di-basics/DefaultGreetingService.cs":::

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:

- Creates a `greeting` given the `name`.
- Calls the `WriteLine` method on the `IConsole` instance.
- Returns the `greeting` to the caller.

The last service to create is the _FarewellService.cs_ file, add the following C# code before continuing:

:::code source="snippets/di/di-basics/FarewellService.cs":::

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.

## Update the `Program` class

Open the _Program.cs_ file and replace the existing code with the following C# code:

:::code source="snippets/di/di-basics/Program.cs":::

The preceding updated code demonstrates the how-to:

- Create a new `ServiceCollection` instance.
- Register and configure services in the `ServiceCollection`:
- The `IConsole` using the implementation factory overload, return a `DefaultConsole` type with the `IsEnabled` set to `true.
- The `IGreetingService` is added with a corresponding implementation type of `DefaultGreetingService` type.
- The `FarewellService` is added as a concrete type.
- Build the `ServiceProvider` from the `ServiceCollection`.
- Resolve the `IGreetingService` and `FarewellService` services.
- Use the resolved services to greet and say goodbye to a person named `David`.

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.

All of these services are registered as singletons, although for this sample, it works identically if they were registered as _transient_ or _scoped_ services.

> [!IMPORTANT]
> 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.

## Run the sample app

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:

```console
Hello, David!
Goodbye, David!
```

### Service descriptors

The most commonly used APIs for adding services to the `ServiceCollection` are lifetime-named generic extension methods, such as:

- `AddSingleton<TService>`
- `AddTransient<TService>`
- `AddScoped<TService>`

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.

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:

:::code source="snippets/di/di-basics/Program.ServiceDescriptors.cs" id="console":::

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:

:::code source="snippets/di/di-basics/Program.ServiceDescriptors.cs" id="greeting":::

The preceding code describes the `IGreetingService` service with its service type, implementation type, and lifetime. Finally, consider the equivalent code for the `FarewellService` service:

:::code source="snippets/di/di-basics/Program.ServiceDescriptors.cs" id="farewell":::

The preceding code describes the concrete `FarewellService` type as both the service and implementation types. The service is registered as a singleton service.

## See also

- [.NET dependency injection](dependency-injection.md)
- [Dependency injection guidelines](dependency-injection-guidelines.md)
- [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
3 changes: 2 additions & 1 deletion docs/core/extensions/dependency-injection-guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Dependency injection guidelines
description: Discover effective dependency injection guidelines and best practices for developing .NET apps. Deepen your understanding of inversion of control.
author: IEvangelist
ms.author: dapine
ms.date: 02/28/2024
ms.date: 07/18/2024
ms.topic: conceptual
---

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

- [Dependency injection in .NET](dependency-injection.md)
- [Understand dependency injection basics in .NET](dependency-injection-basics.md)
- [Tutorial: Use dependency injection in .NET](dependency-injection-usage.md)
7 changes: 4 additions & 3 deletions docs/core/extensions/dependency-injection-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Use dependency injection
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#.
author: IEvangelist
ms.author: dapine
ms.date: 07/08/2024
ms.date: 07/18/2024
ms.topic: tutorial
no-loc: [Transient, Scoped, Singleton, Example]
---
Expand Down Expand Up @@ -126,5 +126,6 @@ From the app output, you can see that:

## See also

* [Dependency injection guidelines](dependency-injection-guidelines.md)
* [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
- [Dependency injection guidelines](dependency-injection-guidelines.md)
- [Understand dependency injection basics in .NET](dependency-injection-basics.md)
- [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
13 changes: 5 additions & 8 deletions docs/core/extensions/dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Dependency injection
description: Learn how to use dependency injection within your .NET apps. Discover how to registration services, define service lifetimes, and express dependencies in C#.
author: IEvangelist
ms.author: dapine
ms.date: 06/03/2024
ms.date: 07/18/2024
ms.topic: overview
---

Expand Down Expand Up @@ -110,18 +110,14 @@ With dependency injection terminology, a service:
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>:

```csharp
public class Worker : BackgroundService
public sealed class Worker(ILogger<Worker> logger) : BackgroundService
{
private readonly ILogger<Worker> _logger;

public Worker(ILogger<Worker> logger) =>
_logger = logger;

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

await Task.Delay(1_000, stoppingToken);
}
}
Expand Down Expand Up @@ -450,6 +446,7 @@ public class ExampleService

## See also

- [Understand dependency injection basics in .NET](dependency-injection-basics.md)
- [Use dependency injection in .NET](dependency-injection-usage.md)
- [Dependency injection guidelines](dependency-injection-guidelines.md)
- [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
Expand Down
14 changes: 14 additions & 0 deletions docs/core/extensions/snippets/di/di-basics/DefaultConsole.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
internal sealed class DefaultConsole : IConsole
{
public bool IsEnabled { get; set; } = true;

void IConsole.WriteLine(string message)
{
if (IsEnabled is false)
{
return;
}

Console.WriteLine(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
internal sealed class DefaultGreetingService(
IConsole console) : IGreetingService
{
public string Greet(string name)
{
var greeting = $"Hello, {name}!";

console.WriteLine(greeting);

return greeting;
}
}
11 changes: 11 additions & 0 deletions docs/core/extensions/snippets/di/di-basics/FarewellService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
public class FarewellService(IConsole console)
{
public string SayGoodbye(string name)
{
var farewell = $"Goodbye, {name}!";

console.WriteLine(farewell);

return farewell;
}
}
4 changes: 4 additions & 0 deletions docs/core/extensions/snippets/di/di-basics/IConsole.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public interface IConsole
{
void WriteLine(string message);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public interface IGreetingService
{
string Greet(string name);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Microsoft.Extensions.DependencyInjection;

internal partial class Program
{
internal static void AddConsole(IServiceCollection services)
{
// <console>
services.Add(ServiceDescriptor.Describe(
serviceType: typeof(IConsole),
implementationFactory: static _ => new DefaultConsole
{
IsEnabled = true
},
lifetime: ServiceLifetime.Singleton));
// </console>
}

public static void AddGreetingService(IServiceCollection services)
{
// <greeting>
services.Add(ServiceDescriptor.Describe(
serviceType: typeof(IGreetingService),
implementationType: typeof(DefaultGreetingService),
lifetime: ServiceLifetime.Singleton));
// </greeting>
}

public static void AddFarewellService(IServiceCollection services)
{
// <farewell>
services.Add(ServiceDescriptor.Describe(
serviceType: typeof(FarewellService),
implementationType: typeof(FarewellService),
lifetime: ServiceLifetime.Singleton));
// </farewell>
}
}
24 changes: 24 additions & 0 deletions docs/core/extensions/snippets/di/di-basics/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.Extensions.DependencyInjection;

// 1. Create the service collection.
var services = new ServiceCollection();

// 2. Register (add and configure) the services.
services.AddSingleton<IConsole>(
implementationFactory: static _ => new DefaultConsole
{
IsEnabled = true
});
services.AddSingleton<IGreetingService, DefaultGreetingService>();
services.AddSingleton<FarewellService>();

// 3. Build the service provider from the service collection.
var serviceProvider = services.BuildServiceProvider();

// 4. Resolve the services that you need.
var greetingService = serviceProvider.GetRequiredService<IGreetingService>();
var farewellService = serviceProvider.GetRequiredService<FarewellService>();

// 5. Use the services
var greeting = greetingService.Greet("David");
var farewell = farewellService.SayGoodbye("David");
14 changes: 14 additions & 0 deletions docs/core/extensions/snippets/di/di-basics/di-basics.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions docs/fundamentals/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -991,6 +991,9 @@ items:
- name: Overview
href: ../core/extensions/dependency-injection.md
displayName: dependency injection,di,ioc,ioc container,dependency container,inversion of control
- name: Dependency injection basics
href: ../core/extensions/dependency-injection-basics.md
displayName: dependency injection basics,di basics,ioc basics,ioc container basics,dependency container basics,inversion of control basics
- name: Use dependency injection
href: ../core/extensions/dependency-injection-usage.md
displayName: use dependency injection,di,di examples,ioc,ioc container,dependency container,inversion of control
Expand Down
Loading