ServiceCollectionHostedServiceExtensions.AddHostedService Method

Definition

Overloads

AddHostedService<THostedService>(IServiceCollection)

Source:
ServiceCollectionHostedServiceExtensions.cs
Source:
ServiceCollectionHostedServiceExtensions.cs
Source:
ServiceCollectionHostedServiceExtensions.cs

Add an IHostedService registration for the given type.

C#
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddHostedService<THostedService> (this Microsoft.Extensions.DependencyInjection.IServiceCollection services) where THostedService : class, Microsoft.Extensions.Hosting.IHostedService;

Type Parameters

THostedService

An IHostedService to register.

Parameters

services
IServiceCollection

The IServiceCollection to register with.

Returns

The original IServiceCollection.

Remarks

Note

You shouldn't call this method multiple times for the same class. Doing so will only register the first HostedService you provide. To add multiple HostedServices, use AddSingleton<TService>(IServiceCollection) for each implementation of IHostedService explicitly.

Applies to

.NET 9 (package-provided) and other versions
Product Versions
.NET 8 (package-provided), 9 (package-provided)
.NET Framework 4.7 (package-provided), 4.7.1 (package-provided), 4.7.2 (package-provided), 4.8 (package-provided)
.NET Standard 2.0 (package-provided), 2.1 (package-provided)

AddHostedService<THostedService>(IServiceCollection, Func<IServiceProvider,THostedService>)

Source:
ServiceCollectionHostedServiceExtensions.cs
Source:
ServiceCollectionHostedServiceExtensions.cs
Source:
ServiceCollectionHostedServiceExtensions.cs

Add an IHostedService registration for the given type.

C#
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddHostedService<THostedService> (this Microsoft.Extensions.DependencyInjection.IServiceCollection services, Func<IServiceProvider,THostedService> implementationFactory) where THostedService : class, Microsoft.Extensions.Hosting.IHostedService;

Type Parameters

THostedService

An IHostedService to register.

Parameters

services
IServiceCollection

The IServiceCollection to register with.

implementationFactory
Func<IServiceProvider,THostedService>

A factory to create new instances of the service implementation.

Returns

The original IServiceCollection.

Remarks

Note

You shouldn't call this method multiple times for the same class. Doing so will only register the first HostedService you provide. To add multiple HostedServices, use AddSingleton<TService>(IServiceCollection, Func<IServiceProvider,TService>) for each implementation of IHostedService explicitly.

Applies to

.NET 9 (package-provided) and other versions
Product Versions
.NET 8 (package-provided), 9 (package-provided)
.NET Framework 4.7 (package-provided), 4.7.1 (package-provided), 4.7.2 (package-provided), 4.8 (package-provided)
.NET Standard 2.0 (package-provided), 2.1 (package-provided)