我希望在批处理中处理相关消息,例如使用Rebus服务总线在相同范围/事务中使用相同处理程序(相同实例)处理事件CustomerCreated和PreferredCustomer。
同一个处理程序同时处理两个消息/事件:
class CustomerHandler : IHandleMessages<CustomerCreated>, IHandleMessages<PreferredCustomer>
{
Customer Customer { get; set; }
public CustomerHandler() {
Customer = new Customer();
}
public void Handle(CustomerCreated message) {
Customer.Name = message.Name;
Console.WriteLine(Customer);
}
public void Handle(PreferredCustomer message) {
Customer.Rebate = message.Rebate;
Console.WriteLine(Customer);
}
}
发送消息时,我使用批处理操作(在NServiceBus中传输消息)
bus.Advanced.Batch.Publish(
new CustomerCreated() { Name = "Anders" },
new PreferredCustomer() { Rebate = 10 });
为了控制处理程序的生命周期,我使用了Windsor Castle的Scoped lifestyle
_container.Register(
Component.For<IHandleMessages<CustomerCreated>, IHandleMessages<PreferredCustomer>>)
.ImplementedBy<CustomerHandler>().LifestyleScoped());
和一个实例化ScopedUnitOfWork的自定义UnitOfWorkManager
class CustomUnitOfWorkManager : IUnitOfWorkManager
{
private readonly IWindsorContainer _container;
public CustomUnitOfWorkManager(IWindsorContainer container) {
_container = container;
}
public IUnitOfWork Create() {
return new ScopedUnitOfWork(_container);
}
}
class ScopedUnitOfWork : IUnitOfWork
{
private readonly IDisposable _scope;
public ScopedUnitOfWork(IWindsorContainer container) {
// Begin transaction
_scope = container.BeginScope();
}
public void Dispose() {
_scope.Dispose();
}
public void Commit() {
// Commit transaction
Console.WriteLine("Commiting");
}
public void Abort() {
// Rollback transaction
Console.WriteLine("Aborting!!!");
}
}
最后配置Rebus使用CustomUnitOfWorkManager
var bus = Configure.With(new WindsorContainerAdapter(_container))
.Transport(t => t.UseMsmqAndGetInputQueueNameFromAppConfig())
.MessageOwnership(d => d.FromRebusConfigurationSection())
.Events(x => x.AddUnitOfWorkManager(new CustomUnitOfWorkManager(_container)))
.CreateBus()
.Start();
这个方法正确吗?
我有限的测试表明这应该可以工作。我甚至可以将其扩展为在ScopedUnitOfWork中包含针对数据存储的事务管理。
听起来你已经搞定了:)
如果你得到正确的提交/回滚行为,那么我会说它很好,很好。
如果你对另一种方法感兴趣,你可能想看看PerTransportMessage
Castle Windsor作用域访问器——它可以这样使用:
container.Register(
Component
.For<ISomething>()
.ImplementedBy<Whatever>()
.LifestyleScoped<PerTransportMessage>()
);
应该能够达到完全相同的行为