Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created November 18, 2024 15:15
Show Gist options
  • Save AldeRoberge/6979d93db63dbcb185a6d4091ecd8eea to your computer and use it in GitHub Desktop.
Save AldeRoberge/6979d93db63dbcb185a6d4091ecd8eea to your computer and use it in GitHub Desktop.
Different instance C# .NET dependency injection DI register hosted service singleton

Using .NET Dependency Injection (DI) for Shared Instances

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:

Solution: Register the Implementation as a Singleton First

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment