I am trying to figure out how to make ASP.NET Core 3.1 start more than a single hosted service so I can run some stuff periodically in the background. I've read a ton of similar questions (e.g., this one) and as far as I understand it's important to return the task from StartAsync()
immediately. That's also how StartAsync()
from the BackgroundService class is implemented.
However, even if I reduce my own code to the bare minimum, only the first service that gets registered is being executed (read: correctly started and stopped when shutting down the server):
type Foo() =
interface IHostedService with
member this.StartAsync ct =
printfn "Start Foo"
Task.CompletedTask
member this.StopAsync ct =
printfn "Stop Foo"
Task.CompletedTask
type Bar() =
interface IHostedService with
member this.StartAsync ct =
printfn "Start Bar"
Task.CompletedTask
member this.StopAsync ct =
printfn "Stop Bar"
Task.CompletedTask
let configureServices (services : IServiceCollection) =
services
.AddHostedService<Foo>()
.AddHostedService<Bar> |> ignore
When the application is started, this results in:
watch : Started
Start Foo
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://[::]:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
^Cwatch : info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
Shutdown requested. Press Ctrl+C again to force exit.
Stop Foo
watch : Exited
So my question is: Did I hit a bug, or do I miss something?