Rebus Saga несколько раз запускает IAmInitiatedBy

Я использую последнюю версию Rebus (0.99.35) вместе с SimpleInjector (3.1.2). В моем первом примере проекта я использую SQL Server для транспорта и Sagas.

Проблема в том, что метод Saga Handle(StartTheSagaMessage message), реализующий IAmInitiatedBy<StartTheSagaMessage>, вызывается 5 раз, и я не могу понять, почему. Кроме того, этот метод публикует сообщение, которое никогда не принимается шиной.

Вот код для настройки:

var container = new Container();

var assemblies = AppDomain.CurrentDomain.GetAssemblies()
    .Where(i => i.FullName.StartsWith("Messages"));

container.RegisterCollection(typeof(IHandleMessages<>), assemblies);

var bus = Configure.With(new SimpleInjectorContainerAdapter(container))
    .Logging(l => l.Trace())
    .Transport(t => t.UseSqlServer(connectionstring, "Messages", "consumer"))
    .Routing(r => r.TypeBased().MapAssemblyOf<Job>("consumer"))
    .Sagas(s => s.StoreInSqlServer(connectionstring, "Sagas", "SagaIndexTable"))
    .Options(o =>
    {
        o.SetNumberOfWorkers(1);
        o.SetMaxParallelism(1);
    })
    .Start();

container.Verify();

bus.Subscribe<Step1FinishedMessage>().Wait();
bus.Subscribe<Step2FinishedMessage>().Wait();

var procId = Guid.NewGuid();
bus.Send(new StartTheSagaMessage() { ProcessId = procId });

И код саги:

public class MySaga : Saga<MySagaData>,
    IAmInitiatedBy<StartTheSagaMessage>,
    IHandleMessages<Step1FinishedMessage>,
    IHandleMessages<Step2FinishedMessage>
{
    public IBus Bus { get; set; }

    protected override void CorrelateMessages(ICorrelationConfig<MySagaData> config)
    {
        config.Correlate<StartTheSagaMessage>(m => m.ProcessId, s => s.SagaProcessId);
        config.Correlate<Step1FinishedMessage>(m => m.ProcessId, s => s.SagaProcessId);
        config.Correlate<Step2FinishedMessage>(m => m.ProcessId, s => s.SagaProcessId);
    }

    public async Task Handle(StartTheSagaMessage message)
    {
        if (IsNew == false)
            return;

        Trace.TraceInformation("Mysaga - got StartTheSagaMessage: {0}", message.ProcessId);
        //The saga is started - Do some stuff - call webservices (in external handler)
        //When this step is finished the external process replies with a "step1FinishedMessage"
        this.Data.SagaProcessId = message.ProcessId;
        //Fake Step1FinishMessage (should be replied from external handler)
        await Bus.Send(new Step1FinishedMessage() { ProcessId = this.Data.SagaProcessId });
    }

    public async Task Handle(Step1FinishedMessage message)
    {
        Trace.TraceInformation("Mysaga - got Step1FinishedMessage: {0}", message.ProcessId);
        //Sagabehaviour when the Step1 is finished by the external handler
        this.Data.Step1Finished = true;
        //After dalying 10 seconds - Send a step2finishedmessage
        await Bus.Defer(TimeSpan.FromSeconds(10), new Step2FinishedMessage() { ProcessId = this.Data.SagaProcessId });
    }

    public async Task Handle(Step2FinishedMessage message)
    {
        await Task.Run(() =>
        //return Task.FromResult<void>(() => 
        {
            Trace.TraceInformation("Mysaga - got Step2FinishedMessage: {0}", message.ProcessId);
            //Step2 is handled - finished the saga
            this.Data.Step2Finished = true;
            this.MarkAsComplete();
        });
    }
}

Полный образец основан на решении, доступном здесь.

Что я делаю неправильно?

Спасибо за помощь.


person ilcorvo    schedule 03.03.2016    source источник
comment
решение доступно здесь использует Autofac?   -  person qujck    schedule 03.03.2016
comment
Да, это так. Исходное решение также использует старые пакеты nuget.   -  person ilcorvo    schedule 03.03.2016
comment
Да, я вижу, и обновление всех пакетов приводит к тому, что код не компилируется.   -  person qujck    schedule 03.03.2016
comment
К сожалению, мне не удалось найти образец с сагами, использующими новые пакеты.   -  person ilcorvo    schedule 03.03.2016
comment
Откуда это SimpleInjectorContainerAdapter?   -  person Steven    schedule 03.03.2016
comment
Является ли: nuget.org/packages/Rebus.SimpleInjector/0.99.34   -  person ilcorvo    schedule 03.03.2016


Ответы (1)


Я изменил сагу и чем она работает.

Я кладу:

    private IBus _bus;

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

На месте:

    public IBus Bus { get; set; }

И тогда это работает! Я не могу понять, почему, потому что отладочная шина не была нулевой внутри метода.

person ilcorvo    schedule 03.03.2016
comment
5 вызовов указывают на то, что, должно быть, произошла ошибка. Вы должны проверить журнал, чтобы увидеть, что было не так. Если вы регистрируетесь в выводе трассировки, вам, вероятно, следует настроить какой-то прослушиватель трассировки, который передает журналы куда-то в файл - в качестве альтернативы (и это то, что я бы рекомендовал) использовать одну из хороших доступных библиотек ведения журналов .NET, например отличный Serilog - person mookid8000; 03.03.2016
comment
К сожалению, сообщения в журнале не было. Спасибо за предложение о Serilog. - person ilcorvo; 15.03.2016