2

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,039
  • 2
  • 21
  • 35

1 Answers1

3

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
  • 2,488
  • 4
  • 23
  • 53