Created
June 28, 2021 15:26
-
-
Save slavanap/01ae7929daced226d331f340e5a05b43 to your computer and use it in GitHub Desktop.
HostedMultiService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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