CodexBloom - Programming Q&A Platform

implementing Scoped Services in ASP.NET Core - 'best practices for scoped service from root provider'

👀 Views: 2 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
asp.net-core dependency-injection scoped-services C#

I'm not sure how to approach Quick question that's been bugging me - I'm working with a question with dependency injection in my ASP.NET Core 6 application... I have a service that is registered as scoped, but I'm trying to access it from a singleton service, which is causing the behavior: `want to resolve scoped service 'MyApp.Services.IMyScopedService' from root provider`. I've registered my services in the `Startup.cs` as follows: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyScopedService, MyScopedService>(); services.AddSingleton<IMySingletonService, MySingletonService>(); } ``` In `MySingletonService`, I have a method that needs to call a method from `IMyScopedService`. I tried injecting `IMyScopedService` directly into the constructor of `MySingletonService`, but it results in the aforementioned behavior. Here's the relevant part of my singleton service: ```csharp public class MySingletonService : IMySingletonService { private readonly IServiceProvider _serviceProvider; public MySingletonService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public void SomeMethod() { using (var scope = _serviceProvider.CreateScope()) { var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>(); scopedService.DoWork(); } } } ``` In this approach, I create a scope within the singleton service to resolve the scoped service, but I'm unsure if this is the best practice. I've seen suggestions that indicate it might lead to other issues such as resource management or unintentional service lifetimes. I'm particularly concerned about whether this is a reliable way to handle scoped services from singletons, or if there are better patterns or practices I should be using instead. Any insights or recommendations would be greatly appreciated! My development environment is macOS. How would you solve this?