Best practise for multiple implementations of IHostedService

146 views Asked by At

I have an application which acts as a gateway has two processes in it and they are continuously processing a stream of events. Both of the Processes have start and stop methods on them. They talk to each other via an event queue.

public class ServiceComposite: IHostedService
{
    public ServiceComposite(IServiceA serviceA, IServiceB serviceB)
    {
        this.serviceA = serviceA;
        this.serviceB = serviceB;
    }

    public Task StartAsync(CancellationToken token)
    {
        return Task.Run(() => 
        {
            Console.Writeline("Starting services");
            serviceA.Start();
            serviceB.Start();
        }, token);
    }

    public Task StopAsync(CancellationToken token)
    {
        return Task.Run(() => 
        {
            Console.Writeline("Stopping services");
            serviceA.Stop();
            serviceB.Stop();
        }, token);
    }
}

At first I wanted to create an interface with a start and stop method on it because then I could just inject an IEnumerable and loop through it to start and stop. But then I saw that IHostedService has a very similar interface with StartAsync and StopAsync.

What are the pros and cons of keeping them as I originally had it, i.e. a single IHostedService implementation which control both processes and the pros and cons of turning my process into an IHostService and register both with

services.AddHostedService<ServiceA>();
services.AddHostedService<ServiceB>();
0

There are 0 answers