为什么要为事件接口层次结构中的每个级别创建一个订阅?

Why is a subscription created for each level in the event interface hierarchy?

我正在尝试了解如何通过使用 masstransit 和 azure 服务总线来正确发布和使用事件。我想使用接口作为我的消息契约,我的事件继承了接口层次结构。

我的消费者将消费多种类型的事件;据我了解,"ReceiveEndpoint" 是最佳选择,因为 "SubscriptionEndpoint" 指定了一种消息类型。 我知道 ASB 不支持多态性。

为单个事件接口设置接收端点时,会为层次结构中的每个级别创建一个订阅:

    public interface IBasiestEventInterface { string P1 { get; } }
    public interface IBaserEventInterface : IBasiestEventInterface { string P2 { get; } }
    public interface IBaseEventInterface : IBaserEventInterface { string P3 { get; } }

    public class TheEvent : IBaseEventInterface
    {
        public string P1 { get; } = "A";
        public string P2 { get; } = "B";
        public string P3 { get; } = "C";
    }

    [TestFixture]
    public class MassTransitTests
    {
        [Test]
        public async Task CanBeConsumedAsInterfaceType()
        {
            var semaphore = new SemaphoreSlim(0);

            var publisher = Bus.Factory.CreateUsingAzureServiceBus(c =>
            {
                c.Host(MassTransitTestsHelper.BusConnectionString, h => { });
            });

            var consumer1 = Bus.Factory.CreateUsingAzureServiceBus(c =>
            {
                c.Host(MassTransitTestsHelper.BusConnectionString, h => { });
                c.ReceiveEndpoint("test_receive_endpoint", e =>
                {
                    e.Handler((MessageHandler<IBaseEventInterface>) (_ =>
                    {
                        semaphore.Release();
                        return Task.CompletedTask;
                    }));
                });
            });

            await publisher.StartAsync();
            await consumer1.StartAsync();

            await publisher.Publish<IBaseEventInterface>(new TheEvent());

            (await semaphore.WaitAsync(10.Seconds())).Should().BeTrue();
        }
    }

消息已按预期收到。看起来订阅中的 "forward to" 到 属性 与层次结构级别相关。额外订阅的目的是在 Azure 服务总线上添加多态事件调度吗?

是的,多态订阅已添加到 Azure 服务总线,这就是你看到额外订阅的原因。因此,您可以订阅消费者中的接口并发布您想要的任何类型,并且实现的接口应该像 RabbitMQ 一样适当地路由。