Skip to content

Instantly share code, notes, and snippets.

@slavanap
Created June 28, 2021 15:26
Show Gist options
  • Save slavanap/01ae7929daced226d331f340e5a05b43 to your computer and use it in GitHub Desktop.
Save slavanap/01ae7929daced226d331f340e5a05b43 to your computer and use it in GitHub Desktop.
HostedMultiService
public static class HostedServicesExtensions {
private class HostedMultiService<THostedService> : IHostedService where THostedService : class, IHostedService {
readonly THostedService[] _hostedServices;
public HostedMultiService(IEnumerable<THostedService> hostedServices) {
_hostedServices = hostedServices.ToArray();
if (_hostedServices.Any(s => s == null))
throw new ArgumentNullException(nameof(hostedServices));
}
public Task StartAsync(CancellationToken cancellationToken) =>
Task.WhenAll(_hostedServices.Select(s => s.StartAsync(cancellationToken)));
public Task StopAsync(CancellationToken cancellationToken) =>
Task.WhenAll(_hostedServices.Select(s => s.StopAsync(cancellationToken)));
}
public static IServiceCollection AddHostedMultiService<THostedService>(this IServiceCollection services, Func<IServiceProvider, IEnumerable<THostedService>> factory)
where THostedService : class, IHostedService => services.AddHostedService(provider => new HostedMultiService<THostedService>(factory(provider)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment