C# Reference ยท Classes and Object-Oriented Concepts
Dependency injection
Reference for dependency injection in C#: constructor injection, Microsoft.Extensions.DependencyInjection, singleton, scoped and transient lifetimes, scope validation.
Dependency injection (DI) means a class receives the objects it needs from outside instead of creating them itself. The class declares its dependencies as constructor parameters, usually typed as interfaces, and something else decides which implementation to pass. That makes classes easier to test (pass a fake) and to change (swap the implementation in one place).
.NET ships a DI container in the Microsoft.Extensions.DependencyInjection namespace. You register services in a ServiceCollection, build a ServiceProvider and ask it for objects. The container reads each constructor, resolves the parameters recursively and caches instances according to the service lifetime.
var services = new ServiceCollection(); services.AddSingleton<IClock, SystemClock>(); services.AddTransient<ReportService>(); using var provider = services.BuildServiceProvider(); var report = provider.GetRequiredService<ReportService>();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services) IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services) IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services) ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) T GetRequiredService<T>(this IServiceProvider provider) where T : notnull T? GetService<T>(this IServiceProvider provider) IServiceScope CreateScope(this IServiceProvider provider)
| Name | Description |
|---|---|
AddSingleton |
One instance for the whole container. Created on first request (or supplied as an instance). |
AddScoped |
One instance per scope. In ASP.NET Core a scope is one HTTP request. |
AddTransient |
A new instance every time the service is requested. |
GetRequiredService<T> |
Returns the service or throws InvalidOperationException if it is not registered. |
GetService<T> |
Returns the service or null if not registered. |
ValidateScopes |
Throws when a scoped service is resolved from the root provider or injected into a singleton. |
ValidateOnBuild |
Checks at build time that all registered services can be constructed. |
Usage notes
- Constructor injection is the default. The container picks the constructor whose parameters it can satisfy. Primary constructors work the same way.
- Captive dependencies. A singleton that takes a scoped or transient service keeps it alive for the whole application. Turn on
ValidateScopesto catch the scoped case early. - Disposal. The container disposes
IDisposableservices it created when the scope or provider is disposed. Instances you pass in yourself (AddSingleton(instance)) are not disposed by the container. - Service locator is an anti-pattern. Injecting
IServiceProviderand callingGetServiceinside business classes hides dependencies. Use it only in factories and composition code. - Several implementations. Register more than one implementation of an interface and request
IEnumerable<IService>to get all of them; a single request gets the last registered. - Keyed services (.NET 8+):
AddKeyedSingleton<IService, Impl>("name")and[FromKeyedServices("name")]. - Not in the box. Property injection, auto-registration by scanning and decorators need extra libraries or hand-written code.
- Console apps can use the full host (
Host.CreateApplicationBuilder) for DI, configuration and logging together.