When using .NET Dependency Injection (DI), if you register a HostedService
and also register it as a Singleton
, the consuming classes might not get the same instance because the DI container creates separate instances for each registration by default.
services.AddHostedService<Database>();
services.AddSingleton<IDatabase, Database>();
To fix this, you need to ensure the same instance is shared between the IHostedService
and the IDatabase
. Here’s how you can do it: