业务逻辑层中的事务

时间:2013-10-04 12:43:15

标签: c# .net design-patterns orm n-tier-architecture

我从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;
                    }
                }
            }
        }
    } 

1 个答案:

答案 0 :(得分:0)

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