CodexBloom - Programming Q&A Platform

ASP.NET Core 6.0 - implementing Dependency Injection in Scoped Services

πŸ‘€ Views: 89 πŸ’¬ Answers: 1 πŸ“… Created: 2025-05-31
asp.net-core dependency-injection services csharp

I'm trying to configure I'm working with an scenario with dependency injection in my ASP.NET Core 6.0 application where scoped services are not being resolved correctly. I have a service `MyScopedService` that depends on `IMyDependency`, which is registered as a transient service. However, when I try to use `MyScopedService` in my controller, I receive the behavior: `Unable to resolve service for type 'IMyDependency' while attempting to activate 'MyScopedService'.` Here’s how I have registered my services in `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddTransient<IMyDependency, MyDependency>(); services.AddScoped<MyScopedService>(); services.AddControllers(); } ``` And my controller looks like this: ```csharp [ApiController] [Route("api/[controller]")] public class MyController : ControllerBase { private readonly MyScopedService _myScopedService; public MyController(MyScopedService myScopedService) { _myScopedService = myScopedService; } } ``` I’ve checked that `MyDependency` is properly registered and available for injection. The scenario seems to arise when `MyScopedService` is instantiated as it tries to resolve `IMyDependency`. I’ve also tried changing `IMyDependency` to scoped instead of transient, but that resulted in a different behavior: `want to resolve scoped service from root provider.` which I understand is due to trying to resolve a scoped service outside of an HTTP request. Is there a recommended pattern for using transient dependencies within a scoped service? Or am I missing something in my service registration? Any guidance would be appreciated!