MassTransit Consumer 为注册消费者引发“未找到消息类型 {type} 的约定”异常

JD *_*vis 6 c# masstransit rabbitmq asp.net-core

我有一个简单的服务,可以接受 HTTP 端点的请求。端点的操作使用 MassTransit 发布事件,提醒消费者实体已更新。然后,已发布事件的使用者向我的同步使用者发送同步请求以完成工作单元。

但是,当事件使用者尝试分派请求时,MassTransit 会抛出异常,并提示A convention for the message type {type} was not found。这似乎意味着我的消费者尚未注册,但我相信是这样。

这是我的Startup注册码:

public void ConfigureServices(IServiceCollection services)
{
    // -- removed non MassTransit code
    services.AddMassTransit(x =>
    {
        x.SetKebabCaseEndpointNameFormatter();
        x.AddConsumers(typeof(Startup).Assembly);
        x.UsingRabbitMq((context, cfg) =>
        {
            var rabbitMq = Configuration.GetSection("RabbitMq");
            var url = rabbitMq.GetValue<string>("Url");
            var username = rabbitMq.GetValue<string>("Username");
            var password = rabbitMq.GetValue<string>("Password");
            
            cfg.Host(url, h =>
            {
                h.Username(username);
                h.Password(password);
            });
            cfg.ConfigureEndpoints(context);
        });
    });
    services.AddMassTransitHostedService();
}
Run Code Online (Sandbox Code Playgroud)

我的 API 控制器如下所示:

[Route("~/api/[controller]")]
public class JobSchedulingController : ApiControllerBase
{
    private readonly IPublishEndpoint _publishEndpoint;

    public JobSchedulingController(IPublishEndpoint publishEndpoint)
    {
        _publishEndpoint = publishEndpoint;
    }

    [HttpPost]
    public async Task<IActionResult> UpdateJob(JobSchedulingInputModel model)
    {
        await _publishEndpoint.Publish<JobSchedulerJobUpdated>(model);
        return Ok();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是事件消费者:

public class JobSchedulerJobUpdatedConsumer 
    : IConsumer<JobSchedulerJobUpdated>
{
    public async Task Consume(
        ConsumeContext<JobSchedulerJobUpdated> context)
    {
        await context.Send<SyncJobSchedulingToLacrm>(context.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,同步请求消费者:

public class SyncJobSchedulingToLacrmConsumer 
    : IConsumer<SyncJobSchedulingToLacrm>
{
    private readonly LacrmClient _client;
    private readonly JobSchedulingContext _context;

    public SyncJobSchedulingToLacrmConsumer(
        LacrmClient client, 
        JobSchedulingContext context)
    {
        _client = client;
        _context = context;
    }

    public async Task Consume(ConsumeContext<SyncJobSchedulingToLacrm> context)
    {
        await context.Publish<JobSchedulerSyncedToLacrm>(new
        {
            LacrmPipelineItemId = ""
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我从事件使用者内部收到错误,但它从未到达同步使用者。什么可能导致这种行为?

Chr*_*son 8

您正在调用Send,这是一种方便的方法。

     await context.Send<SyncJobSchedulingToLacrm>(context.Message);
Run Code Online (Sandbox Code Playgroud)

如果您尚未为该消息类型配置 EndpointConvention,则它将找不到。

我建议阅读这个答案:https ://stackoverflow.com/a/62714778/1882