Microsoft.Extensions.ServiceCollectionExtensions
Namespace: Microsoft.Extensions.DependencyInjection
Extensions for IServiceCollection.
AddSingleton<TService>()
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>()
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>()
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>()
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>();
}