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:
Instead of registering it twice, you can register it as a Singleton
and then use it for both interfaces:
services.AddSingleton<Database>(); // Register the implementation as Singleton
services.AddSingleton<IHostedService>(provider => provider.GetRequiredService<Database>()); // Use the same instance