Every time that i try to call Send from MediatR to any Query/Command that i have, it returns this Exception:
System.InvalidOperationException: 'Error constructing handler for request of type MediatR.IRequestHandler
2[CQRSHost.Recursos.Queries.GetTodosProdutosQuery,System.Collections.Generic.IEnumerable1[CQRSHost.Models.Produto]]. Register your handlers with the container. See the samples in GitHub for examples.'
Inner Exception:
InvalidOperationException: Cannot resolve 'MediatR.IRequestHandler
2[CQRSHost.Recursos.Queries.GetTodosProdutosQuery,System.Collections.Generic.IEnumerable1[CQRSHost.Models.Produto]]' from root provider because it requires scoped service 'CQRSHost.Context.AppDbContext'.
But i have the AppDbContext in my DI container:
public static IHostBuilder CreateHostBuilder(string[] args)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
return Host.CreateDefaultBuilder(args)
.UseSerilog()
.UseEnvironment("Development")
.ConfigureHostConfiguration(hostConfig =>
{
hostConfig.SetBasePath(Directory.GetCurrentDirectory());
hostConfig.AddEnvironmentVariables("DSO_");
})
.ConfigureServices((context, services) =>
{
services.AddSingleton(ConfigureLogger());
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
"Server=localhost;Database=newdatabase;User Id=sa;Password=P@ssw0rd!@#$%;",
b => b.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName)));
services.AddHostedService<NewService>();
//services.AddMediatR(Assembly.GetExecutingAssembly());
//services.AddMediatR(typeof(GetTodosProdutosQuery).GetTypeInfo().Assembly);
services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies());
});
}
Here is the service that i use to call the query:
public class NewService : IHostedService
{
private readonly ILogger _logger;
private readonly IMediator _mediator;
public NewService(ILogger logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var command = new GetTodosProdutosQuery();
var response = await _mediator.Send(command);
_logger.Information($"First Name: {response.First()?.Nome}");
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
And here is what my project looks like: ProjectImage
The commented lines is what i've already tryied to solve.
What am i doing wrong?