使用EventStore时如何集成到NServiceBus?
我是NSB和ES的新手,并试图在使用ES和CQRS时找出NSB的最佳设置。
我和示例中的DispatchCommit一样挂钩NSB, https://github.com/joliver/EventStore/blob/master/doc/EventStore.Example/MainProgram.cs
非常感谢一些代码或指导。
答案 0 :(得分:4)
以下是我在制作中使用的内容:
public sealed class NServiceBusPublisher : IPublishMessages
{
private const string AggregateIdKey = "AggregateId";
private const string CommitVersionKey = "CommitVersion";
private const string EventVersionKey = "EventVersion";
private const string BusPrefixKey = "Bus.";
private readonly IBus bus;
public NServiceBusPublisher(IBus bus)
{
this.bus = bus;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public void Publish(Commit commit)
{
for (var i = 0; i < commit.Events.Count; i++)
{
var eventMessage = commit.Events[i];
var busMessage = eventMessage.Body as IMessage;
AppendHeaders(busMessage, commit.Headers); // optional
AppendHeaders(busMessage, eventMessage.Headers); // optional
AppendVersion(commit, i); // optional
this.bus.Publish(busMessage);
}
}
private static void AppendHeaders(IMessage message, IEnumerable<KeyValuePair<string, object>> headers)
{
headers = headers.Where(x => x.Key.StartsWith(BusPrefixKey));
foreach (var header in headers)
{
var key = header.Key.Substring(BusPrefixKey.Length);
var value = (header.Value ?? string.Empty).ToString();
message.SetHeader(key, value);
}
}
private static void AppendVersion(Commit commit, int index)
{
var busMessage = commit.Events[index].Body as IMessage;
busMessage.SetHeader(AggregateIdKey, commit.StreamId.ToString());
busMessage.SetHeader(CommitVersionKey, commit.StreamRevision.ToString());
busMessage.SetHeader(EventVersionKey, GetSpecificEventVersion(commit, index).ToString());
}
private static int GetSpecificEventVersion(Commit commit, int index)
{
// e.g. (StreamRevision: 120) - (5 events) + 1 + (index @ 4: the last index) = event version: 120
return commit.StreamRevision - commit.Events.Count + 1 + index;
}
}
答案 1 :(得分:2)
在NSB的第三个版本中引入了名为Unobtrusive mode的功能。有了它,您可以摆脱域中的NSB依赖。
NServiceBus V3中的这一新功能允许您传递自己的功能 用于确定哪些类型是消息定义的约定 使用IMessage,ICommand或IEvent接口。