Microsoft.Extensions.ServiceCollectionExtensions

Namespace: Microsoft.Extensions.DependencyInjection

Extensions for IServiceCollection.

AddSingleton<TService>()

public static IServiceCollection AddSingleton<TService>(this IServiceCollection services) where TService : class

Adds a singleton service of the type specified by TService to the specified IServiceCollection. A singleton service is instantiated the first time it is requested. Subsequent requests for the same service will return the same instance.

Parameters

  • services: The IServiceCollection to add the service to.

Returns

The IServiceCollection so that calls can be chained.

C# Example

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IMyService, MyService>();
}

AddSingleton<TService, TImplementation>()

public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : TService, class

Adds a singleton service of the type specified by TService to the specified IServiceCollection. A new instance of the specified TImplementation is created when the first reference to the service is required.

Parameters

  • services: The IServiceCollection to add the service to.

Returns

The IServiceCollection so that calls can be chained.

C# Example

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfiguration, ConfigurationManager>();
}

AddScoped<TService>()

public static IServiceCollection AddScoped<TService>(this IServiceCollection services) where TService : class

Adds a scoped service of the type specified by TService to the specified IServiceCollection. A scoped service has the same lifetime as a request in the current scope.

Parameters

  • services: The IServiceCollection to add the service to.

Returns

The IServiceCollection so that calls can be chained.

C# Example

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IDataContext>();
}

AddTransient<TService>()

public static IServiceCollection AddTransient<TService>(this IServiceCollection services) where TService : class

Adds a transient service of the type specified by TService to the specified IServiceCollection. A transient service is instantiated every time it is requested.

Parameters

  • services: The IServiceCollection to add the service to.

Returns

The IServiceCollection so that calls can be chained.

C# Example

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ILogger>();
}