IServiceCollection Interface

Microsoft.Extensions.DependencyInjection

Represents a collection of service descriptors that can be used to define the services available for dependency injection.

Summary

The IServiceCollection interface is central to configuring dependency injection in .NET applications. It provides a fluent API to register services and their corresponding implementation types or factory functions. Services registered with an IServiceCollection can then be used to create a ServiceProvider, which is responsible for resolving those services.

Key operations include adding transient, scoped, and singleton services, as well as configuring options and adding delegates for service creation.

Members

See Also

Example Usage:


using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public interface IMyService
{
    void DoSomething();
}

public class MyService : IMyService
{
    public void DoSomething()
    {
        Console.WriteLine("Doing something...");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var myService = scope.ServiceProvider.GetRequiredService<IMyService>();
            myService.DoSomething();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
            {
                // Add a transient service
                services.AddTransient<IMyService, MyService>();

                // Add a singleton service with a factory
                services.AddSingleton<ISingletonService>(provider => new SingletonService(provider.GetRequiredService<IOptions<MySettings>>().Value));

                // Configure options
                services.Configure<MySettings>(context.Configuration.GetSection("MySettings"));
            });
}

public class MySettings
{
    public string SomeSetting { get; set; }
}

public interface ISingletonService { }
public class SingletonService : ISingletonService
{
    public SingletonService(MySettings settings) { }
}