0

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;
                    }
                }
            }
        }
    } 
Community
  • 1
  • 1
GorillaApe
  • 3,611
  • 10
  • 63
  • 106

1 Answers1

0

I think you need to go toward implementing a UnitOfWork that can be passed/shared amongst those who wish to partake in a single 'transaction'.

David Osborne
  • 6,436
  • 1
  • 21
  • 35
  • Create an interface that represents the UnitOfWork and then create an MsSql-specific implementation. Make you service classes dependent on the interface and then you can pass the implementation around. This way your services can use the current UnitOfWork or start a new one, etc. – David Osborne Oct 05 '13 at 08:39
  • how can it be passed around ? Parameter- Property ? – GorillaApe Oct 05 '13 at 09:05
  • DI'd via constructor, usually. – David Osborne Oct 05 '13 at 09:31