Namespace: Microsoft.Extensions.DependencyInjection

Assembly: Microsoft.Extensions.DependencyInjection.Abstractions

Content: Types

Namespace Microsoft.Extensions.DependencyInjection

Provides types for configuring and managing dependency injection containers in .NET applications.

Summary of Members

Interfaces

Name Description
IServiceCollection Represents a collection of service descriptors that can be used to register services with a dependency injection container.
IServiceProvider Represents an object that can provide services.
IServiceScope Represents a scope that contains resolved services.
IServiceScopeFactory Creates an IServiceScope which contains a resolved instance of the specified service.
ServiceDescriptor Describes a service registration.

Classes

Name Description
ServiceCollection A default implementation of IServiceCollection.
ServiceManager Represents a service container that can resolve services based on registered descriptors.

Extension Methods

Name Description
Extension ServiceCollectionExtensions Provides extension methods for adding services to an IServiceCollection.

Common Usage Patterns

The Microsoft.Extensions.DependencyInjection namespace is fundamental to modern .NET development, especially in ASP.NET Core and other host-based applications. Here are some common patterns:

Registering Services

You typically register services in an IServiceCollection. The extension methods on ServiceCollectionExtensions make this concise:


using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();

// Register a singleton service
services.AddSingleton<IMyService, MyService>();

// Register a scoped service
services.AddScoped<IAnotherService, AnotherService>();

// Register a transient service
services.AddTransient<IFoo, Foo>();

// Register a service with a factory
services.AddTransient<IBaz>(provider => new Baz(provider.GetRequiredService<ILogger<Baz>>()));
            

Building the Service Provider

Once services are registered, you build an IServiceProvider to resolve them:


var serviceProvider = services.BuildServiceProvider();
            

Resolving Services

You can resolve services from the IServiceProvider:


IMyService myService = serviceProvider.GetRequiredService<IMyService>();
IAnotherService anotherService = serviceProvider.GetService<IAnotherService>(); // Can return null
            

Scopes

For scoped services, you need to create an IServiceScope:


using (var scope = serviceProvider.CreateScope())
{
    var scopedService = scope.ServiceProvider.GetRequiredService<IAnotherService>();
    // Use scopedService within this scope
}
            

Related Topics