1
votes

I am trying to register, my users, using CQRS.

I am registering MediatR:

services.AddMediatR(typeof(MyCommand).GetTypeInfo().Assembly);


public class Handler : IRequestHandler<RegisterCommand, object>
        {
            private readonly MyDbContext _context;
            private readonly IMediator _mediator;
            private readonly UserManager<User> _userManager;

            public Handler(IYawaMVPDbContext context, IMediator mediator, UserManager<User> userManager)
            {
                _context = context;
                _mediator = mediator;
                _userManager = userManager;
            }
}

I am getting the following exceptions:

InvalidOperationException: Unable to resolve service for type 'MyDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore6[MyCore.Domain.Entities.User,MyCore.MyApp.Persistence.MyDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]'. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)

InvalidOperationException: Error constructing handler for request of type MediatR.IRequestHandler`2[MyCore.MyApp.Application.Users.Commands.Register.RegisterCommand,System.Object].

Register your handlers with the container. See the samples in GitHub for examples.

Any help appreciated.

2

2 Answers

0
votes

Add service to resolve the DbContext in the startup file

services.AddDbContext<IYawaMVPDbContext, YourDbContextImplementation>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("yourConnectionString")));
0
votes

I think the following code has no issue

services.AddMediatR(typeof(MyCommand).GetTypeInfo().Assembly);

handles all the MediatR IRequest and IRequestHandlers.

but you created an IYawaMVPDbContext interface and its implementation class which can't be handled by that MediatR.Extensions.Microsoft.DependencyInjection

DBContext are registered with dependency injection during application startup so that they can be provided automatically to components that consume services - manually register this like

services.AddDbContext<IYawaMVPDbContext, DbContextImplementation>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));