将中间件添加到MassTransit发布渠道

时间:2016-05-02 03:00:44

标签: c# masstransit

我正在构建一个系统,其中包含通过发布订阅模式进行通信的组件。我需要为我发布的每条消息传递某些上下文数据。我想特别使用Thread.CurrentPrincipal来丰富传出管道上的消息。

这是我到目前为止的代码:

public class AddPrincipalFilter<T> : IFilter<T> where T : class, PipeContext
{
    public void Probe(ProbeContext context)
    {
    }

    public async Task Send(T context, IPipe<T> next)
    {
        var msg = context.GetPayload<MessageBase>();
        msg.Principal = Thread.CurrentPrincipal;

        await Console.Out.WriteLineAsync("AddUserIdFilter");
        await next.Send(context);
    }
}

public class AddPrincipalSpecification<T> :
    IPipeSpecification<T> where T : class, PipeContext
{
    public void Apply(IPipeBuilder<T> builder)
    {
        Console.Out.WriteLineAsync("In Apply");
        builder.AddFilter(new AddPrincipalFilter<T>());
    }

    public IEnumerable<ValidationResult> Validate()
    {
        return Enumerable.Empty<ValidationResult>();
    }
}

public  static class AddPrincipalExtensions
{
    public static void UseAddPrincipalFilter<T>(this IPipeConfigurator<T> configurator)
        where T : class, PipeContext
    {
        Console.Out.WriteLineAsync("In UserPrincipalFilter");
        configurator.AddPipeSpecification(new AddPrincipalSpecification<T>());
    }
}

var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
    IRabbitMqBusFactoryConfigurator x;
    var host = cfg.Host(new Uri("rabbitmq://localhost"),
        h =>
        {
            h.Username("guest");
            h.Password("guest");
        });
        cfg.UseAddUserFilter();
});

bus.Publish(new TestMessage { Name = "Jeff" });

正确配置中间件(或者更确切地说,调用了UseAddPrincipalFilter和Apply方法),但AddPrincipalFilter.Send永远不会被调用,因此消息不会被CurrentPrincipal丰富。

为了在发布时调用中间件,还有什么我应该做的吗?

0 个答案:

没有答案