Multiple Instances of HostedService
Asked Answered
T

1

6

I want to run multiple instances of the same hosted service. I tried registering them twice:

services.AddHostedService<MyService>();
services.AddHostedService<MyService>();

But ExecuteAsync is only called on one instance.

However if I have two different services:

services.AddHostedService<MyServiceA>();
services.AddHostedService<MyServiceB>();

ExecuteAsync is called on each one.

Is there anyway to run the same instance twice? I in essence want to have two worker services doing the same thing.

Turtleneck answered 12/3, 2021 at 5:54 Comment(0)
M
7

The behavior is changed in .net core now and AddHostedService is now adds a Singleton instead of the Transient service. So you can try this:

services.AddSingleton<IHostedService, MyService>();

See this and this

Metzger answered 12/3, 2021 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.