业务逻辑层中的事务
本文关键字:事务 业务 | 更新日期: 2023-09-27 18:33:50
我从 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;
}
}
}
}
}
我认为你需要实现一个可以在那些希望参与单个"交易"的人之间传递/共享的UnitOfWork。