In the Startup.ConfigureServices I'm adding MassTransit configuration
services.AddMassTransit(config =>
{
config.SetKebabCaseEndpointNameFormatter();
config.AddRequestClient<RegisterCarOwner>();
config.AddBus(provider => Bus.Factory.CreateUsingRabbitMq();
});
services.AddMassTransitHostedService();
in the handler I'm using this client in order to send message
public class RegisterCarOwnerHandler : IRequestHandler<RegisterCarOwnerCommand, Unit>
{
private readonly IRequestClient<RegisterCarOwner> _registerOwnerClient;
public RegisterCarOwnerHandler(IRequestClient<RegisterCarOwner> registerOwnerClient)
{
_registerOwnerClient = registerOwnerClient
}
public async Task<Unit> Handle(RegisterCarOwnerCommand command, CancellationToken token)
{
...
}
}
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler2[xxxx.RegisterCarOwnerCommand] Lifetime: Transient ImplementationType: xxxx.TestHandler': Unable to resolve service for type 'MassTransit.IRequestClient
1[RegisterCarOwner.RegisterCarOwnerHandler]' while attempting to activate 'xxxx.RegisterCarOwnerHandler '.)'
Update:
public class Startup
{
public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
....
var rabbitMqConf = new RabbitMqConfiguration();
this.Configuration.GetSection(RabbitMqConfiguration.SectionName).Bind(rabbitMqConf);
services.AddMassTransit(x =>
{
x.AddRequestClient<RegisterCarOwner>();
x.UsingRabbitMq((context, cfg) =>
{
cfg.SetKebabCaseEndpointNameFormatter();
cfg.Host(new Uri(rabbitMqConf.ConnectionUrl), c =>
{
c.Username(rabbitMqConf.Username);
c.Password(rabbitMqConf.Password);
});
cfg.ConfigureEndpoints(context);
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
....
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
CodePudding user response:
IRequestClient<T>
is scoped, and you're trying to resolve it without a scope.
Also, your bus configuration is seriously outdated, change:
config.AddBus(provider => Bus.Factory.CreateUsingRabbitMq();
to the supported syntax:
config.UsingRabbitMq((context, cfg) => {});