开发者

Rollback transaction in Repository from another class

well my problem is: I have a method like:

class Manager
{
    void method1()
    {
        // save object in database to get ID
        int newId = this.Repository.Save(obj);

        try {
            // call remote webservice to save another object with same ID as in local DB
            webservice.Save(remoteObj, id); 
        }
        catch(Exception e)
        {
            // do Rollback in Repository here
        }
    }
}

Bassically this is the code. Repository use NHibernate to save to DB. I need to save in DB to know the new ID and then send this ID to webservice. If something fail calling webservice I want to rollback and discard saved object.... and here is my problem. I can't open and control a transaction in Repository from my class Manager.

I already try with this also:

class Manager
{
    void method1()
    {
        using (TransactionScope scope = new TransactionScope())
        {
           // save object in database to get ID
           int newId = this.Repository.Save(obj);

           // call remote webse开发者_C百科rvice to save another object with same ID 
           // as in local DB
           webservice.Save(remoteObj, id); 
           scope.Complete();
        }
    }
}

Here the problem is that the rollback is OK but not the Save(Create in NHibernate). I get error about that object "Transaction" is not found or the transaction is already closed just after the line : "scope.Complete();".

I think that something is wrong trying to control NHibernate transaction with TransactionScope .

I dont know if is a problem about approach, maybe another way should be used to handle this situation... ??

any help or idea where to find ??

Thanks a lot !!


Assuming you already have an opened session in a CurrentSession property/variable and that you could pass that working session to your repository, I would do the following:

using(var trx = CurrentSession.BeginTransaction())
{
    try
    {
        int newId = this.Repository.Save(obj, CurrentSession);  
        webservice.Save(remoteObj, id);

        trx.Commit();
    }
    catch
    {
        trx.Rollback();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜