Coree.NETStandard
  • API
Show / Hide Table of Contents
  • Coree.NETStandard.Abstractions.DependencySingleton
    • DependencySingleton<T>
    • IDependencySingleton
  • Coree.NETStandard.Abstractions.FluentBase
    • FluentBase
    • IFluentBase
  • Coree.NETStandard.Abstractions.InitializationService
    • InitializationDependentServices
    • InitializationService
  • Coree.NETStandard.Abstractions.ServiceFactory
    • ServiceFactory<T>
  • Coree.NETStandard.Abstractions.ServiceFactoryEx
    • ServiceFactoryEx<T>
    • ServiceFactoryEx<T, K, R, S, U, V, W, X, Y, Z>
    • ServiceFactoryEx<T, K>
    • ServiceFactoryEx<T, K, R>
    • ServiceFactoryEx<T, K, R, S>
    • ServiceFactoryEx<T, K, R, S, U>
    • ServiceFactoryEx<T, K, R, S, U, V>
    • ServiceFactoryEx<T, K, R, S, U, V, W>
    • ServiceFactoryEx<T, K, R, S, U, V, W, X>
    • ServiceFactoryEx<T, K, R, S, U, V, W, X, Y>
  • Coree.NETStandard.Classes.AsyncEventCollection
    • AsyncEventCollection<T>
    • AsyncEventCollection<T>.CustomEventDelegate
  • Coree.NETStandard.Classes.CommonDistinguishedNameBuilder
    • CommonDistinguishedNameBuilder
    • DistinguishedName
  • Coree.NETStandard.Classes.Criteria
    • CriteriaComparisonMethod
    • CriteriaEnumerableExtensions
    • CriteriaExpressionBuilder
    • CriteriaItem<TValue>
    • CriteriaItems
    • CriteriaOperator
    • CriteriaQueryableExtensions
  • Coree.NETStandard.Classes.HttpRequestService
    • ContentComposer
    • HttpRequestHeadersExtensions
    • HttpRequestService
    • HttpRequestServiceHandler
    • HttpRequestServiceUriExtensions
    • ServiceCollectionExtensions
    • TransactionRecord
  • Coree.NETStandard.Classes.Scheduler
    • Scheduler
    • Scheduler.TickerEventArgs
    • Scheduler.TickerEventDelegate
  • Coree.NETStandard.Classes.ThreadSafeCollection
    • ThreadSafeCollection<T>
  • Coree.NETStandard.Classes.ThreadSafeValue
    • ThreadSafeValue<T>
  • Coree.NETStandard.Classes.TimeOfDay
    • TimeOfDay
  • Coree.NETStandard.Extensions.Collections.Enumerable
    • CollectionsEnumerableExtensions
  • Coree.NETStandard.Extensions.Collections.List
    • CollectionsListExtensions
  • Coree.NETStandard.Extensions.Conversions.ByteArray
    • ConversionsByteArrayExtensions
  • Coree.NETStandard.Extensions.Conversions.HostApplicationBuilder
    • ConversionsHostApplicationBuilderExtensions
  • Coree.NETStandard.Extensions.Conversions.String
    • ConversionsStringExtensions
    • Encodings
  • Coree.NETStandard.Extensions.Conversions.Stringbuilder
    • ConversionsStringbuilderExtension
  • Coree.NETStandard.Extensions.Enums
    • EnumExtensions
  • Coree.NETStandard.Extensions.Http.HttpHeader
    • HttpHeadersExtensions
  • Coree.NETStandard.Extensions.Primitives.Bool
    • PrimitivesBoolExtensions
  • Coree.NETStandard.Extensions.Reflection.ServiceProvider
    • ReflectionServiceProviderExtensions
  • Coree.NETStandard.Extensions.ServiceCollection
    • ServiceCollectionExtensions
  • Coree.NETStandard.Extensions.Threading.CancellationToken
    • ThreadingCancellationTokenExtensions
  • Coree.NETStandard.Extensions.Utilities
    • DateTimeExtensions
  • Coree.NETStandard.Extensions.Validations.String
    • ValidationsStringExtensions
  • Coree.NETStandard.HostedServicesCollection
    • HostedServicesCollectionConfig<T>
    • IHostedServicesCollectionConfig<T>
    • ServiceCollectionExtensions
    • ServiceProviderExtensions
  • Coree.NETStandard.Serilog
    • ConditionalLevelSink
    • CustomTheme
    • LoggerSinkConfigurationExtensions
    • OutputTemplates
    • ServiceCollectionExtensions
    • SourceContextShortEnricher
  • Coree.NETStandard.Services.DebugManagement
    • DebugService
    • IDebugService
  • Coree.NETStandard.Services.DirectoryOperationsManagement
    • DirectoryOperationsService
    • IDirectoryOperationsService
  • Coree.NETStandard.Services.FileManagement
    • FileService
    • IFileService
  • Coree.NETStandard.Services.FileOperationsManagement
    • FileOperationsService
    • FileOperationsService.FileSystemEntry
    • FileOperationsService.FileSystemInformation
    • FileOperationsService.VerifiedCopyStatus
    • IFileOperationsService
  • Coree.NETStandard.Services.HashManagement
    • HashService
    • IHashService
  • Coree.NETStandard.Services.NetworkManagement
    • INetworkService
    • NetworkService
    • NetworkService.IpAdressInformation
    • NetworkService.NetworkInterfaceDetail
  • Coree.NETStandard.Services.ProcessManagement
    • IProcessService
    • ProcessRunExitCodeState
    • ProcessRunResult
    • ProcessService
  • Coree.NETStandard.Services.RuntimeInsightsManagement
    • IRuntimeInsightsService
    • RuntimeInsightsService
  • Coree.NETStandard.SpectreConsole
    • CommandAppExtensions
    • HostBuilderExtensions
    • ServiceCollectionExtensions
    • SpectreConsoleHostedService
    • SpectreConsoleHostedService.ExitCode
    • SpectreConsoleTypeRegistrar
    • SpectreConsoleTypeResolver
  • Coree.NETStandard.UnderConstruction
    • DbContextExtensions
    • HttpClientStatic
    • HttpClientStatic.HttpClientResponse
    • HttpClientStatic.XRate
    • HttpClientStatic.XRateGroup
    • HttpClientStatic.XRateItem
    • IScheduleProvider
    • IntervalScheduleProvider
    • LimitedHistory<T>
    • ScheduleCombiner
    • Scheduler
    • Scheduler.TickerEventArgs
    • Scheduler.TickerEventDelegate
    • Scheduler2
    • Scheduler2.TickerEventArgs
    • Scheduler2.TickerEventDelegate
    • Scheduler3
    • Scheduler3.TickerEventArgs
    • Scheduler3.TickerEventDelegate
    • SqlliteMemoryContext
    • SqlliteMemoryContext.UserDataDto
    • TimedEntry<T>
    • Timing
    • Timing.Ticker
    • Timing.Ticker.TickerEventArgs
    • Timing.TickerSync
    • WeekDayAtScheduleProvider
  • Coree.NETStandard.Utilities
    • EventSubscription
    • MainContext

Class ServiceCollectionExtensions

Provides extension methods for IServiceCollection to facilitate the registration of hosted services with specific configurations.

Inheritance
object
ServiceCollectionExtensions
Inherited Members
object.Equals(object)
object.Equals(object, object)
object.GetHashCode()
object.GetType()
object.MemberwiseClone()
object.ReferenceEquals(object, object)
object.ToString()
Namespace: Coree.NETStandard.HostedServicesCollection
Assembly: Coree.NETStandard.dll
Syntax
public static class ServiceCollectionExtensions

Methods

| Edit this page View Source

AddHostedServicesCollection<T, K>(IServiceCollection, IConfiguration, string)

Registers a collection of hosted services of type T with their configurations loaded from a specified section of the application's IConfiguration.

Declaration
public static IServiceCollection AddHostedServicesCollection<T, K>(this IServiceCollection services, IConfiguration configuration, string sectionName) where T : class, IHostedService where K : class, new()
Parameters
Type Name Description
IServiceCollection services

The IServiceCollection to add the services to.

IConfiguration configuration

The application's configuration.

string sectionName

The name of the configuration section from which to load the configurations.

Returns
Type Description
IServiceCollection

The original IServiceCollection instance with the hosted services registered.

Type Parameters
Name Description
T

The type of the hosted service to register. Must implement IHostedService.

K

The configuration type for the hosted service. Must be a class with a parameterless constructor.

Remarks

Configurations are bound to new instances of K and each hosted service instance is registered with a singleton service descriptor.

//appsettings.json
"ServiceConfigurations": {
    "FooService": {
      "Name": "Service1"
    },
    "BarService": {
      "Name": "Service2"
    }
}

services.AddHostedServicesCollection<MyBackgroundSrv, MyBackgroundSrvConfig>(context.Configuration, "ServiceConfigurations");

public class MyBackgroundSrvConfig
{
    public Guid Guid { get; } = Guid.NewGuid();  public string? Name { get; set; }
}

public class MyBackgroundSrv : BackgroundService
{
    private readonly MyBackgroundSrvConfig options; private readonly ILogger<MyBackgroundService> logger;

    public MyBackgroundSrv(ILogger<MyBackgroundService> logger, IHostedServicesCollectionConfig<MyBackgroundSrvConfig> options)
    {
        this.logger = logger; this.options = options.FetchNextConfig();
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try {
                logger.LogInformation("MyBackgroundSrv running: {Name} with {guid} at {time}", options.Name, options.Guid.ToString(), DateTimeOffset.Now);
                await Task.Delay(5000, stoppingToken);
            }
            catch (TaskCanceledException)
            { logger.LogInformation("MyBackgroundSrv cancel: {Name} with {guid} at {time}", options.Name, options.Guid.ToString(), DateTimeOffset.Now); }
        }
    }
}
| Edit this page View Source

AddHostedServicesCollection<T, K>(IServiceCollection, List<K>)

Registers a collection of hosted services of type T with their configurations specified in a list of K.

Declaration
public static IServiceCollection AddHostedServicesCollection<T, K>(this IServiceCollection services, List<K> values) where T : class, IHostedService where K : class, new()
Parameters
Type Name Description
IServiceCollection services

The IServiceCollection to add the services to.

List<K> values

A list of configuration instances for the hosted services.

Returns
Type Description
IServiceCollection

The original IServiceCollection instance with the hosted services registered.

Type Parameters
Name Description
T

The type of the hosted service to register. Must implement IHostedService.

K

The configuration type for the hosted service. Must be a class with a parameterless constructor.

Remarks
services.AddHostedServicesCollection<MyBackgroundSrv, MyBackgroundSrvConfig>(new List<MyBackgroundSrvConfig>() {
    new() { Name = "Service1"},
    new() { Name = "Service2" }
});

public class MyBackgroundSrvConfig
{
    public Guid Guid { get; } = Guid.NewGuid();
    public string? Name { get; set; }
}

public class MyBackgroundSrv : BackgroundService
{
    private readonly MyBackgroundSrvConfig options;
    private readonly ILogger<MyBackgroundService> logger;

    public MyBackgroundSrv(ILogger<MyBackgroundService> logger, IHostedServicesCollectionConfig<MyBackgroundSrvConfig> options)
    {
        this.logger = logger; this.options = options.FetchNextConfig();
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                logger.LogInformation("MyBackgroundSrv running: {Name} with {guid} at {time}", options.Name, options.Guid.ToString(), DateTimeOffset.Now);
                await Task.Delay(5000, stoppingToken);
            }
            catch (TaskCanceledException)
            {
                logger.LogInformation("MyBackgroundSrv cancel: {Name} with {guid} at {time}", options.Name, options.Guid.ToString(), DateTimeOffset.Now);
            }
        }
    }
}
| Edit this page View Source

AddHostedServicesCollection<T, K>(IServiceCollection, K[])

Registers a collection of hosted services of type T with their configurations specified in an array of K.

Declaration
public static IServiceCollection AddHostedServicesCollection<T, K>(this IServiceCollection services, K[] values) where T : class, IHostedService where K : class, new()
Parameters
Type Name Description
IServiceCollection services

The IServiceCollection to add the services to.

K[] values

An array of configuration instances for the hosted services.

Returns
Type Description
IServiceCollection

The original IServiceCollection instance with the hosted services registered.

Type Parameters
Name Description
T

The type of the hosted service to register. Must implement IHostedService.

K

The configuration type for the hosted service. Must be a class with a parameterless constructor.

Remarks

Each hosted service instance is registered with a singleton service descriptor.

services.AddHostedServicesCollection<MyBackgroundSrv, MyBackgroundSrvConfig>(new MyBackgroundSrvConfig[] {
    new() { Name = "Service1"},
    new() { Name = "Service2" }
});
public class MyBackgroundSrvConfig
{
    public Guid Guid { get; } = Guid.NewGuid();
    public string? Name { get; set; }
}

public class MyBackgroundSrv : BackgroundService
{
    private readonly MyBackgroundSrvConfig options;
    private readonly ILogger<MyBackgroundService> logger;

    public MyBackgroundSrv(ILogger<MyBackgroundService> logger, IHostedServicesCollectionConfig<MyBackgroundSrvConfig> options)
    {
        this.logger = logger; this.options = options.FetchNextConfig();
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                logger.LogInformation("MyBackgroundSrv running: {Name} with {guid} at {time}", options.Name, options.Guid.ToString(), DateTimeOffset.Now);
                await Task.Delay(5000, stoppingToken);
            }
            catch (TaskCanceledException)
            {
                logger.LogInformation("MyBackgroundSrv cancel: {Name} with {guid} at {time}", options.Name, options.Guid.ToString(), DateTimeOffset.Now);
            }
        }
    }
}
  • Edit this page
  • View Source
In this article
Back to top