0

My solution has a ASP.NET Web API project and a Core project that contains the entity framework core DbContext, repository (SeriesRepository : ISeriesRepository), and service that calls the repository (SeriesService : ISeriesService). The API should call the service using dependency injection by adding Builder.Services.AddScoped<ISeriesService, SeriesService>(); in Program.cs. The controller should use the SeriesService via an injected dependency:

private readonly ISeriesService _seriesService;
    
public SeriesController(ISeriesService seriesService)
{
    _seriesService = seriesService;
}

But when I try and run it, I get this exception:

System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Project.Core.Services.ISeriesService Lifetime: Scoped ImplementationType: Project.Core.Services.SeriesService': Unable to resolve service for type 'Project.Core.Repositories.ISeriesRepository' while attempting to activate 'Project.Core.Services.SeriesService'.

If I add the repository Builder.Services.AddScoped<ISeriesRepository, SeriesRepository>(); in Program.cs, it runs successfully. But this seems like it defeats the purpose of using the SeriesService to abstract away the repository/DbContext. If this isn't the correct way, how do I correctly implement this using services/repositories and dependency injection?

Steven
  • 166,672
  • 24
  • 332
  • 435
wjhanna
  • 27
  • 6
  • So the question is "why all dependencies should be registered in the same container"? – Roman Ryzhiy Dec 09 '22 at 15:43
  • "this seems like it defeats the purpose of using the SeriesService to abstract away the repository/DbContext." Why so? `SeriesService` still knows nothing about `SeriesRepository`, but only the `ISeriesRepository` abstraction? Why do you feel registering the `SeriesRepository` defeats the purpose of abstraction? – Steven Dec 09 '22 at 15:46
  • The dependencies have to be registered in the container for ASP.NET to know how to resolve the dependencies. There are some tricks you can do like making a base class that all your dependencies inherit from, add a custom attribute to it and use reflection to add all dependencies that inherit from it to the DI container on startup. – nbokmans Dec 09 '22 at 15:46
  • "Why do you feel registering the SeriesRepository defeats the purpose of abstraction?": Reading about clean architecture, isn't the point to have the data layer (SeriesRepository) accessed by the infrastructure layer (SeriesService) and the presentation layer (API) shouldn't know/care about the data layer, only the infrastructure layer? – wjhanna Dec 09 '22 at 16:05

0 Answers0