简体   繁体   中英

Transactions in business logic layer

I stole the following code from https://stackoverflow.com/a/14988549/294022 .

This seems a great abstraction. However there is a single problem. What if you want to combine multiple service calls?

This works fine combining DAL calls. But for service? Is there a solution?

 public class Foo //POCO for data access
    {
        //Add Attributes for Ormlite
        public int Id { get; set;  }
    }

    public class Bar //POCO for data access
    {
        //Add Attributes for Ormlite
        public int Id { get; set; }
    }

    //your request class which is passed to your service
    public class DeleteById 
    {
        public int Id { get; set; }
    }

    public class FooBarService : MyServiceBase //MyServiceBase has resusable method for handling transactions. 
    {
        public object Post(DeleteById request)
        {
            DbExec(dbConn =>
                       {
                           dbConn.DeleteById<Foo>(request.Id);
                           dbConn.DeleteById<Bar>(request.Id);
                       });

            return null;
        }
    }

    public class MyServiceBase : Service
    {
        public IDbConnectionFactory DbFactory { get; set; }

        protected void DbExec(Action<IDbConnection> actions)
        {
            using (var dbConn = DbFactory.OpenDbConnection())
            {
                using (var trans = dbConn.OpenTransaction())
                {
                    try
                    {
                        actions(dbConn);
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }
    } 

我认为您需要着手实现一个UnitOfWork,可以在希望参与单个“交易”的人员之间传递/共享。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM