26 KiB
author | ms.author | ms.date |
---|---|---|
rick-anderson | riande | 8/17/2024 |
:::moniker range="= aspnetcore-8.0"
By Kirk Larkin, Steve Smith, and Brandon Dahler
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
For more information specific to dependency injection within MVC controllers, see xref:mvc/controllers/dependency-injection.
For information on using dependency injection in applications other than web apps, see Dependency injection in .NET.
For more information on dependency injection of options, see xref:fundamentals/configuration/options.
This topic provides information on dependency injection in ASP.NET Core. The primary documentation on using dependency injection is contained in Dependency injection in .NET.
View or download sample code (how to download)
Overview of dependency injection
A dependency is an object that another object depends on. Examine the following MyDependency
class with a WriteMessage
method that other classes depend on:
A class can create an instance of the MyDependency
class to make use of its WriteMessage
method. In the following example, the MyDependency
class is a dependency of the IndexModel
class:
The class creates and directly depends on the MyDependency
class. Code dependencies, such as in the previous example, are problematic and should be avoided for the following reasons:
- To replace
MyDependency
with a different implementation, theIndexModel
class must be modified. - If
MyDependency
has dependencies, they must also be configured by theIndexModel
class. In a large project with multiple classes depending onMyDependency
, the configuration code becomes scattered across the app. - This implementation is difficult to unit test.
Dependency injection addresses these problems through:
- The use of an interface or base class to abstract the dependency implementation.
- Registration of the dependency in a service container. ASP.NET Core provides a built-in service container, xref:System.IServiceProvider. Services are typically registered in the app's
Program.cs
file. - Injection of the service into the constructor of the class where it's used. The framework takes on the responsibility of creating an instance of the dependency and disposing of it when it's no longer needed.
In the sample app, the IMyDependency
interface defines the WriteMessage
method:
This interface is implemented by a concrete type, MyDependency
:
The sample app registers the IMyDependency
service with the concrete type MyDependency
. The xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddScoped%2A method registers the service with a scoped lifetime, the lifetime of a single request. Service lifetimes are described later in this topic.
In the sample app, the IMyDependency
service is requested and used to call the WriteMessage
method:
By using the DI pattern, the controller or Razor Page:
- Doesn't use the concrete type
MyDependency
, only theIMyDependency
interface it implements. That makes it easy to change the implementation without modifying the controller or Razor Page. - Doesn't create an instance of
MyDependency
, it's created by the DI container.
The implementation of the IMyDependency
interface can be improved by using the built-in logging API:
The updated Program.cs
registers the new IMyDependency
implementation:
MyDependency2
depends on xref:Microsoft.Extensions.Logging.ILogger%601, which it requests in the constructor. ILogger<TCategoryName>
is a framework-provided service.
It's not unusual to use dependency injection in a chained fashion. Each requested dependency in turn requests its own dependencies. The container resolves the dependencies in the graph and returns the fully resolved service. The collective set of dependencies that must be resolved is typically referred to as a dependency tree, dependency graph, or object graph.
The container resolves ILogger<TCategoryName>
by taking advantage of (generic) open types, eliminating the need to register every (generic) constructed type.
In dependency injection terminology, a service:
- Is typically an object that provides a service to other objects, such as the
IMyDependency
service. - Is not related to a web service, although the service may use a web service.
The framework provides a robust logging system. The IMyDependency
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 doesn't require any services to be registered:
Using the preceding code, there is no need to update Program.cs
, because logging is provided by the framework.
Register groups of services with extension methods
The ASP.NET Core framework uses a convention for registering a group of related services. The convention is to use a single Add{GROUP_NAME}
extension method to register all of the services required by a framework feature. For example, the xref:Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddControllers%2A extension method registers the services required for MVC controllers.
The following code is generated by the Razor Pages template using individual user accounts and shows how to add additional services to the container using the extension methods xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContext%2A and xref:Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionUIExtensions.AddDefaultIdentity%2A:
Service lifetimes
See Service lifetimes in Dependency injection in .NET
To use scoped services in middleware, use one of the following approaches:
- Inject the service into the middleware's
Invoke
orInvokeAsync
method. Using constructor injection throws a runtime exception because it forces the scoped service to behave like a singleton. The sample in the Lifetime and registration options section demonstrates theInvokeAsync
approach. - Use Factory-based middleware. Middleware registered using this approach is activated per client request (connection), which allows scoped services to be injected into the middleware's constructor.
For more information, see xref:fundamentals/middleware/write#per-request-middleware-dependencies.
Service registration methods
See Service registration methods in Dependency injection in .NET
It's common to use multiple implementations when mocking types for testing.
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.
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 IMyDependency
as the service type. The second call to AddSingleton
overrides the previous one when resolved as IMyDependency
and adds to the previous one when multiple services are resolved via IEnumerable<IMyDependency>
. Services appear in the order they were registered when resolved via IEnumerable<{SERVICE}>
.
services.AddSingleton<IMyDependency, MyDependency>();
services.AddSingleton<IMyDependency, DifferentDependency>();
public class MyService
{
public MyService(IMyDependency myDependency,
IEnumerable<IMyDependency> myDependencies)
{
Trace.Assert(myDependency is DifferentDependency);
var dependencyArray = myDependencies.ToArray();
Trace.Assert(dependencyArray[0] is MyDependency);
Trace.Assert(dependencyArray[1] is DifferentDependency);
}
}
Keyed services
Keyed services refers to a mechanism for registering and retrieving Dependency Injection (DI) services using keys. A service is associated with a key by calling xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddKeyedSingleton%2A (or AddKeyedScoped
or AddKeyedTransient
) to register it. Access a registered service by specifying the key with the [FromKeyedServices]
attribute. The following code shows how to use keyed services:
:::code language="csharp" source="~/../AspNetCore.Docs.Samples/samples/KeyedServices/Program.cs" highlight="6,7,12-14,39,47":::
Constructor injection behavior
See Constructor injection behavior in Dependency injection in .NET
Entity Framework contexts
By default, Entity Framework contexts are added to the service container using the scoped lifetime because web app database operations are normally scoped to the client request. To use a different lifetime, specify the lifetime by using an xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContext%2A overload. Services of a given lifetime shouldn't use a database context with a lifetime that's shorter than the service's lifetime.
Lifetime and registration options
To demonstrate the difference between service lifetimes and their registration options, consider the following interfaces that represent a task as an operation with an identifier, OperationId
. Depending on how the lifetime of an operation's service is configured for the following interfaces, the container provides either the same or different instances of the service when requested by a class:
The following Operation
class implements all of the preceding interfaces. The Operation
constructor generates a GUID and stores the last 4 characters in the OperationId
property:
The following code creates multiple registrations of the Operation
class according to the named lifetimes:
The sample app demonstrates object lifetimes both within and between requests. The IndexModel
and the middleware request each kind of IOperation
type and log the OperationId
for each:
Similar to the IndexModel
, the middleware resolves the same services:
Scoped and transient services must be resolved in the InvokeAsync
method:
The logger output shows:
- Transient objects are always different. The transient
OperationId
value is different in theIndexModel
and in the middleware. - Scoped objects are the same for a given request but differ across each new request.
- Singleton objects are the same for every request.
To reduce the logging output, set "Logging:LogLevel:Microsoft:Error" in the appsettings.Development.json
file:
Resolve a service at app start up
The following code shows how to resolve a scoped service for a limited duration when the app starts:
Scope validation
See Constructor injection behavior in Dependency injection in .NET
For more information, see Scope validation.
Request Services
Services and their dependencies within an ASP.NET Core request are exposed through xref:Microsoft.AspNetCore.Http.HttpContext.RequestServices?displayProperty=nameWithType.
The framework creates a scope per request, and RequestServices
exposes the scoped service provider. All scoped services are valid for as long as the request is active.
[!NOTE] Prefer requesting dependencies as constructor parameters over resolving services from
RequestServices
. Requesting dependencies as constructor parameters yields classes that are easier to test.
Design services for dependency injection
When designing services for dependency injection:
- Avoid stateful, static classes and members. Avoid creating global state by designing apps to use singleton services instead.
- Avoid direct instantiation of dependent classes within services. Direct instantiation couples the code to a particular implementation.
- Make services small, well-factored, and easily tested.
If a class has a lot of injected dependencies, it might be a sign that the class has too many responsibilities and violates the Single Responsibility Principle (SRP). Attempt to refactor the class by moving some of its responsibilities into new classes. Keep in mind that Razor Pages page model classes and MVC controller classes should focus on UI concerns.
Disposal of services
The container calls xref:System.IDisposable.Dispose%2A for the xref:System.IDisposable types it creates. Services resolved from the container should never be disposed by the developer. If a type or factory is registered as a singleton, the container disposes the singleton automatically.
In the following example, the services are created by the service container and disposed automatically: dependency-injection\samples\6.x\DIsample2\DIsample2\Services\Service1.cs [!code-csharp]
The debug console shows the following output after each refresh of the Index page:
Service1: IndexModel.OnGet
Service2: IndexModel.OnGet
Service3: IndexModel.OnGet, MyKey = MyKey from appsettings.Developement.json
Service1.Dispose
Services not created by the service container
Consider the following code:
In the preceding code:
- The service instances aren't created by the service container.
- The framework doesn't dispose of the services automatically.
- The developer is responsible for disposing the services.
IDisposable guidance for Transient and shared instances
See IDisposable guidance for Transient and shared instance in Dependency injection in .NET
Default service container replacement
See Default service container replacement in Dependency injection in .NET
Recommendations
See Recommendations in Dependency injection in .NET
-
Avoid using the service locator pattern. For example, don't invoke xref:System.IServiceProvider.GetService%2A to obtain a service instance when you can use DI instead:
Incorrect:
Correct:
public class MyClass { private readonly IOptionsMonitor<MyOptions> _optionsMonitor; public MyClass(IOptionsMonitor<MyOptions> optionsMonitor) { _optionsMonitor = optionsMonitor; } public void MyMethod() { var option = _optionsMonitor.CurrentValue.Option; ... } }
-
Another service locator variation to avoid is injecting a factory that resolves dependencies at runtime. Both of these practices mix Inversion of Control strategies.
-
Avoid static access to
HttpContext
(for example, IHttpContextAccessor.HttpContext).
DI is an alternative to static/global object access patterns. You may not be able to realize the benefits of DI if you mix it with static object access.
Recommended patterns for multi-tenancy in DI
Orchard Core is an application framework for building modular, multi-tenant applications on ASP.NET Core. For more information, see the Orchard Core Documentation.
See the Orchard Core samples for examples of how to build modular and multi-tenant apps using just the Orchard Core Framework without any of its CMS-specific features.
Framework-provided services
Program.cs
registers services that the app uses, including platform features, such as Entity Framework Core and ASP.NET Core MVC. Initially, the IServiceCollection
provided to Program.cs
has services defined by the framework depending on how the host was configured. For apps based on the ASP.NET Core templates, the framework registers more than 250 services.
The following table lists a small sample of these framework-registered services:
Additional resources
- xref:mvc/views/dependency-injection
- xref:mvc/controllers/dependency-injection
- xref:security/authorization/dependencyinjection
- xref:blazor/fundamentals/dependency-injection
- NDC Conference Patterns for DI app development
- xref:fundamentals/startup
- xref:fundamentals/middleware/extensibility
- Understand dependency injection basics in .NET
- Dependency injection guidelines
- Tutorial: Use dependency injection in .NET
- .NET dependency injection
- ASP.NET CORE DEPENDENCY INJECTION: WHAT IS THE ISERVICECOLLECTION?
- Four ways to dispose IDisposables in ASP.NET Core
- Writing Clean Code in ASP.NET Core with Dependency Injection (MSDN)
- Explicit Dependencies Principle
- Inversion of Control Containers and the Dependency Injection Pattern (Martin Fowler)
- How to register a service with multiple interfaces in ASP.NET Core DI
:::moniker-end