Search code examples
c#redisrabbitmqmasstransitsaga

(Masstransit Saga with MultiBus) How can i publish message to another bus from Saga?


From Is it possible to have a MassTransit Saga react to events that come from more that one bus (multibus)?

I try to use saga with multibus. But when I inject ISecondBus into Saga. Something is wrong. my program is stuck.

public class TestSaga : MassTransitStateMachine<TestState>
    {
        public TestSaga(ISecondBus secondBus)
        {
            if (secondBus is null)
            {
                throw new ArgumentNullException(nameof(secondBus));
            }
        }    
    }

program.cs

        services.AddMassTransit(x =>
        {
            x.AddSagaStateMachine<TestSaga, TestState>()
             .RedisRepository(redisCfg =>
             {
                 redisCfg.DatabaseConfiguration("127.0.0.1:6379,password=");
             });
            x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                cfg.Host("rabbitmq://127.0.0.1:5672/A", hostConfig =>
                {
                    hostConfig.Username("xxxx");
                    hostConfig.Password("xxxx");
                });
                cfg.ReceiveEndpoint("some-queue", e =>
                {
                    e.PrefetchCount = 1;
                    e.UseInMemoryOutbox();
                    e.ConfigureSaga<TestState>(provider);
                });
            }));
        });

        services.AddMassTransit<ISecondBus>(x =>
        {
            x.AddSagaStateMachine<TestSaga, TestState>()
             .RedisRepository(redisCfg =>
             {
                 redisCfg.DatabaseConfiguration("127.0.0.1:6379,password=");
             });

            x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                cfg.Host("rabbitmq://127.0.0.1:5672/B", hostConfig =>
                {
                    hostConfig.Username("xxx");
                    hostConfig.Password("xxx");
                });

                cfg.ReceiveEndpoint("some-queue", e =>
                {
                    e.PrefetchCount = 1;
                    e.UseInMemoryOutbox();
                    e.ConfigureSaga<TestState>(provider);
                });
            }));
        });

Solution

  • You can't inject runtime dependencies into the saga state machine. If you want to publish to another bus from a state machine, you'll need to create a custom activity and call that from your state machine behavior.

    https://masstransit-project.com/usage/sagas/automatonymous.html#custom