我在 ReBus 中使用 Sagas,根据我使用 NServiceBus 的经验,您可以回复 Saga 的原始创建者以提供更新,如下所示:
Saga<>.ReplyToOriginator
我没有看到使用 ReBus 执行此操作的等效方法。有没有办法做到这一点,如果不是,我可以使用什么是好的模式(发起者轮询除外)来实现同样的事情?一个例子是尝试创建一个客户,而客户在尝试更改其地址之前想知道它是何时创建的。
这是我快速组合的客户场景的一个简单示例:
public class CreateCustomerSaga : Saga<CreateCustomerData>,
IAmInitiatedBy<CreateCustomerCommand>,
IHandleMessages<CustomerUniqunessCheckResult>
{
private readonly IBus _bus;
private readonly ICustomerResourceAccess _customerResourceAccess;
public CreateCustomerSaga(IBus bus, ICustomerResourceAccess customerResourceAccess)
{
_bus = bus;
_customerResourceAccess = customerResourceAccess;
}
public override void ConfigureHowToFindSaga()
{
Incoming<CustomerUniqunessCheckResult>(x => x.IsCustomerUnique).CorrelatesWith(y => y.CustomerId);
}
public void Handle(CreateCustomerCommand message)
{
Data.CustomerId = message.CustomerId;
Data.CustomerName = message.CustomerName;
_bus.Send(new CheckCustomerUniquenessCommand(message.CustomerId));
}
public void Handle(CustomerUniqunessCheckResult message)
{
if (message.IsCustomerUnique)
{
_customerResourceAccess.CreateCustomer(Data.CustomerId, Data.CustomerName);
// This is what seems to be missing from ReBus to reply to the original sender
_bus.?(new CustomerCreatedEvent(Data.CustomerId));
}
else
{
// This is what seems to be missing from ReBus to reply to the original sender
_bus.?(new CustomerAlreadExistsEvent(Data.CustomerId));
}
}
}
public class CustomerCreatedEvent
{
public Guid CustomerId { get; set; }
public CustomerCreatedEvent(Guid customerId)
{
CustomerId = customerId;
}
}
public class CustomerAlreadExistsEvent
{
public Guid CustomerId { get; set; }
public CustomerAlreadExistsEvent(Guid customerId)
{
CustomerId = customerId;
}
}
public class CustomerUniqunessCheckResult
{
public bool IsCustomerUnique { get; set; }
}
public class CheckCustomerUniquenessCommand
{
public CheckCustomerUniquenessCommand(Guid customerId)
{ }
}
public interface ICustomerResourceAccess
{
void CreateCustomer(Guid customerId, string customerName);
}
public class CreateCustomerCommand
{
public Guid CustomerId { get; set; }
public string CustomerName { get; set; }
}
public class CreateCustomerData : ISagaData
{
public CreateCustomerData()
{
Id = Guid.NewGuid();
}
public Guid CustomerId { get; set; }
public string CustomerName { get; set; }
public Guid Id { get; set; }
public int Revision { get; set; }
}
不,不幸的是,目前 Rebus 的 sagas 中没有回复发起者功能。不过,您可以轻松地做到这一点,方法是在像这样创建 saga 时存储发起者的端点(在可以启动 saga 的消息的所有 Handle
方法中):
if (IsNew) {
Data.Originator = MessageContext.GetCurrent().ReturnAddress;
}
然后当您想回复发起人时:
bus.Advanced.Routing.Send(Data.Originator, new HelloThereMyFriend());
虽然我经常考虑将它添加到 Rebus,要么作为 ISagaData
的额外字段,要么作为一个额外的接口(interface) ISagaDataWithOriginator
,您可以选择将其应用于您的传奇数据,但我自己从来没有(足够)需要。
我是一名优秀的程序员,十分优秀!