這是一個更概念性的問題。 我正在寫在使用ORM的事務基於服務器的客戶端應用程序。基本上這意味着每一層都知道如何與例如這裏的事務塊的工作是Web服務層實現:交易和事件一起
public HandleTransaction<TReturn>(Action<TReturn>)
{
bool opendByMe = false;
// Some static transaction manager
var transactionMgr = GetTransactionManager();
try
{
// If not opened before me
if(!transactionMgr.IsActive)
{
transactionMgr.BeginTransaction();
opendByMe = true;
}
// Run the action
var returnValue = action();
// If we opened the transaction then we should close it
if(opendByMe)
{
transactionMgr.Commit();
}
return returnValue;
}
catch
{
if(opendByMe)
{
if(transactionMgr.IsActive)
{
// Rollback only if i opened the transaction
transactionMgr.Rollback();
}
}
// Else, bubble exception
throw;
}
}
public void ServiceWork1()
{
// Subscribe to person event
PersonBL.PersonChanged += HandlePersonChanged(Person pers);
HandleTransaction(() =>
{
// BL actions are made in a bulk.. If one of them fails the transaction
// should be rolled back
PersonBL.CreatePerson("Jeff");
PersonBL.CreatePerson("John");
PersonBL.CreatePerson("Peter");
};)
}
public void HandlePersonChanged(Person pers)
{
// Notify some one
}
該作品很好,但現在我想添加一些事件到我的應用 即PersonCreatedEvent ..問題是整合事件冒泡與事務..在上面的例子中可以說,PersonBL.CreatePerson()方法觸發一個「PersonChanged」事件服務層。然後服務層處理這個事件並將事件發送給客戶端..但是我不想在我確信事務已經提交之前觸發這些事件。 BL層不知道我的商業交易邏輯,所以它在CreatePerson方法中激發事件..
是否有任何設計解決方案僅在完成交易後才堆疊/處理我訂閱的事件?
爲了簡化我的問題:我想在一個批量執行HandlePersonChanged只有在提交後..
您可以使用新方法在業務層內移動事務,並創建另一個事件,如'BatchOfPersonChanged'而不是'PersonChanged'。 –