在消费者

时间:2016-08-09 19:08:35

标签: masstransit

我试图在Consumer.Consume方法中启动请求/响应,并且正在努力填充总线参数。

public class DeleteUserConsumer : IConsumer<IDeleteUser>
{
    public async Task Consume(ConsumeContext<IDeleteUser> context) 
    {
        var address = "rabbitmq://host/vhost/queue"
        var timeout = TimeSpan.FromSeconds(15);
        var bus = context.??? // was hoping to get an IBusControl instance from the context - but perhaps this isn't possible?

        IRequestClient<IGetUserDetails,IUserDetails> client = new MessageRequestClient<IGetUserDetails, IUserDetails>(bus, address, timeout);
        var userDetails = await client.Request(new IGetUserDetails() {Name = context.Message.Name});
    }
}

忽略任意示例,是否有任何机制来获取对IBusControl实例的引用以传递给MessageRequestClient构造函数?

1 个答案:

答案 0 :(得分:1)

我建议您按照以下步骤使用您的代码找到一个快乐的地方。

首先,更新您的类以接受IBus参数:

public class DeleteUserConsumer : 
    IConsumer<IDeleteUser>
{
    IBus _bus;

    public DeleteUserConsumer(IBus bus)
    {
        _bus = bus;
    }

    public async Task Consume(ConsumeContext<IDeleteUser> context) 
    {
        var address = "rabbitmq://host/vhost/queue"
        var timeout = TimeSpan.FromSeconds(15);

        IRequestClient<IGetUserDetails,IUserDetails> client = new MessageRequestClient<IGetUserDetails, IUserDetails>(_bus, address, timeout);
        var userDetails = await client.Request(new IGetUserDetails() {Name = context.Message.Name});
    }
}

接下来,更新您的使用者注册以包含用于创建使用者的工厂方法:

IBusControl busControl = null;
busControl = Bus.Factory.CreateUsingInMemory(x =>
{
    x.ReceiveEndpoint("my_service", e =>
    {
        e.Consumer(() => new DeleteUserConsumer(busControl));
    })
})

闭包应该捕获对变量的引用,它应该可以正常传递参数。然后,它应该工作!