Search code examples
c#dependency-injectionservicecqrsmediatr

Unable to resolve IDbContext while activating Service


Working in CQRS with MediatR, in Startup I register the DomainEventDispatcher, the Repos, Query- and Eventhandlers and the Services. The repos work with DbContext and so do my services. Everything CRUD works until I inject my Service in the Controller, I get the following error: Unable to resolve service for type 'IDbContext' while attempting to activate 'Service'.

I Find it strange seeing as I

    services.AddDbContext<DbContext>(options =>
      {
        options.UseLazyLoadingProxies().UseSqlServer(cs);
        options.EnableSensitiveDataLogging(true);
      });

before registering the following:

services
.AddScoped<IDomainEventsDispatcher, DomainEventsDispatcher>()
.AddScoped<IRepo<ToDoItem>, EfCRepo<ToDoItem>>()
.AddMediatR(cfg => cfg.AsScoped(), typeof(ToDoItemsQueryHandler).GetTypeInfo().Assembly)
.AddScoped<INotificationHandler<Event>, EventHandler>()
.AddMediatR(cfg => cfg.AsScoped(), typeof(EventHandler).GetTypeInfo().Assembly);
.AddScoped<IService, Service>()

When I try to AddScoped the IDbContext with the

AddScoped<IDbContext, DbContext>()

My Context is empty and cannot Get entities from Db anymore.

I find it strange that I would need to AddScoped the IDbContext for the services, seeing as the Repos work with the DbContext as well, without needing to resolve service for type IDbContext.

I've looked at MediatR official documentation and couldn't find anything on how to register Services, and googling 'register services MediatR startup' redirects mostly to other issues, so any help/insights from you guys is more than welcome!

I've made a new question as I can dependency inject, but somehow seems different for services. Most questions on S/O regarding registering in startup are more generic to my feeling.

Thanks in advance!


Solution

  • For future references: The solution was indeed to add

    AddScoped<IDbContext, DbContext>()
    

    Must have been something else that broke my context