Understanding “Finalize” in MassTransit

2019-06-01 05:20发布

问题:

I'm having some trouble understanding how Finalize() works in MassTransit, and specifically whether it can be executed during the initial state. Setup:

public Event<ICrawlRequestCreated> CrawlCreated { get; private set; }
public Event CrawlFailed { get; private set; }

public State Executing { get; private set; }
public State Completed { get; private set; }
public State Failed { get; private set; }

public WorkflowSaga()
{
    InstanceState(x => x.CurrentState);

    Initially(
        When(CrawlCreated)
            .Then(HandleCrawlRequestCreated)
            .TransitionTo(Executing),
        When(CrawlFailed)
            .Then(HandleCrawlFailed)
            .TransitionTo(Failed)
            .Finalize()
    );

    ...

    SetCompletedWhenFinalized();
}

If I catch an exception in HandleCrawlRequestCreated, I raise CrawlFailed, like so:

context.Raise(CrawlFailed);

which fires HandleCrawlFailed correctly, but it doesn't remove the state machine instance from the repository (SQL Server via EF). But if I raise CrawlFailed during the executing state, the instance is removed from the repository. What am I missing?

回答1:

You should use the .Catch() methods, instead of catching the exception in your method, and within the .Catch you can finalize instead of transitioning to the Executing state.

If you Finalize in Initial, it shouldn't ever persist the state machine to the database, but I didn't write the EF repository and I'm not sure the test coverage ensures that to be the case.