CodexBloom - Programming Q&A Platform

C# 10 - guide with Lazy Initialization of Singleton Service with Scoped Dependencies in ASP.NET Core

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
aspnet-core dependency-injection singleton C#

Quick question that's been bugging me - I've been struggling with this for a few days now and could really use some help... I'm working with an scenario with lazy initialization of a singleton service that depends on a scoped service in my ASP.NET Core application. The singleton service is registered using `services.AddSingleton<LazySingletonService>()`, which relies on a scoped service injected through its constructor. When I try to access the singleton service in my controller, I'm getting an `InvalidOperationException` with the message: "want to consume scoped service 'ScopedService' from singleton 'LazySingletonService'". I understand that a singleton should not depend on a scoped service, but I want to use lazy initialization without running into this scenario. I've attempted to refactor my code by injecting the `IServiceProvider` into my singleton service and resolving the scoped dependency within the method that actually uses it, as shown below: ```csharp public class LazySingletonService { private readonly IServiceProvider _serviceProvider; public LazySingletonService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public async Task DoWorkAsync() { using (var scope = _serviceProvider.CreateScope()) { var scopedService = scope.ServiceProvider.GetRequiredService<ScopedService>(); await scopedService.ExecuteAsync(); } } } ``` However, I'm still unsure if this is the best practice in terms of performance and maintainability. Is there a more optimal way to structure this? Are there any potential pitfalls with this approach that I should be aware of? Also, how would you handle exceptions that might occur when resolving scoped services within a singleton? Any insights would be greatly appreciated. Any help would be greatly appreciated!