implementing Configuring Dependency Injection for Scoped Services in ASP.NET Core 6
I tried several approaches but none seem to work. I'm having trouble with the configuration of dependency injection for scoped services in my ASP.NET Core 6 application. I registered a service as scoped but when I try to inject it into my controllers, I'm getting an `InvalidOperationException` stating that the service is not available for the current context. The service in question is a simple repository that accesses my database: ```csharp public interface IMyRepository { Task<MyEntity> GetEntityAsync(int id); } public class MyRepository : IMyRepository { private readonly MyDbContext _context; public MyRepository(MyDbContext context) { _context = context; } public async Task<MyEntity> GetEntityAsync(int id) { return await _context.MyEntities.FindAsync(id); } } ``` In my `Startup.cs`, I registered the service like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped<IMyRepository, MyRepository>(); services.AddControllers(); } ``` Then, in my controller, I have: ```csharp public class MyController : ControllerBase { private readonly IMyRepository _repository; public MyController(IMyRepository repository) { _repository = repository; } [HttpGet("{id}")] public async Task<IActionResult> Get(int id) { var entity = await _repository.GetEntityAsync(id); if (entity == null) return NotFound(); return Ok(entity); } } ``` However, when I run the application and try to access the endpoint, I receive the following behavior: ``` InvalidOperationException: want to consume scoped service 'IMyRepository' from singleton 'MyController'. ``` I understand that scoped services want to be injected into singleton instances, but I thought controllers were created per request and therefore should be scoped. I've checked the middleware pipeline, and it seems to be configured correctly. I've also ensured that I'm not trying to resolve the controller elsewhere, or that I'm not inadvertently creating a singleton instance of it. What could be going wrong here? I've tried using the `AddTransient` registration for my repository, but that does not feel like the right solution. Any insights would be greatly appreciated! Is there a simpler solution I'm overlooking?