0

我从https://stackoverflow.com/a/14988549/294022窃取了以下代码。

这似乎是一个很好的抽象。但是,有一个问题。如果你想组合多个服务调用怎么办?

这可以很好地结合 DAL 调用。但是为了服务?有解决办法吗?

 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;
                    }
                }
            }
        }
    } 
4

1 回答 1

0

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

于 2013-10-04T15:09:52.653 回答