CodexBloom - Programming Q&A Platform

How to implement guide with dependency injection of generic repositories in asp.net core 6 - type mismatch scenarios

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-06
asp.net-core dependency-injection repository-pattern C#

I've been working on this all day and I'm working on a personal project and Quick question that's been bugging me - I'm working with a type mismatch behavior when trying to inject a generic repository into my ASP.NET Core 6 application. I've set up a generic repository pattern, but when I try to use it in my controller, I'm getting the behavior: `InvalidOperationException: Unable to resolve service for type 'MyApp.Repositories.IGenericRepository`1[MyApp.Models.MyEntity]' while attempting to activate 'MyApp.Controllers.MyEntityController'`. Here's how I registered my services in `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>)); services.AddScoped<IMyEntityService, MyEntityService>(); } ``` And in my controller, I'm attempting to inject the repository like this: ```csharp [ApiController] [Route("api/[controller]")] public class MyEntityController : ControllerBase { private readonly IGenericRepository<MyEntity> _repository; public MyEntityController(IGenericRepository<MyEntity> repository) { _repository = repository; } } ``` I’ve confirmed that `MyEntity` is a valid class and implements the necessary interfaces if required. I've tried a few variations on how I register the services, but the scenario continues. Any insights on why the DI container is unable to resolve the generic repository? I also checked to ensure that the namespaces are correct and there are no typos in the interface names.