4

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.

user472292
  • 1,069
  • 2
  • 22
  • 37

1 Answers1

6

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

Ask
  • 3,076
  • 6
  • 30
  • 63