【发布时间】:2015-03-27 17:56:27
【问题描述】:
在我的项目中,单一的服务方法是一个业务事务。例如,假设我有以下服务/存储库:
public interface IDocumentService {
void CreateDocument(Document doc);
void AttachFileToDocument(int documentId, string filepath);
}
public class DocumentService
{
private readonly IDocumentRepository _repository;
public DocumentService(IDocumentRepository repository)
{
_repository = repository;
}
public void CreateDocument(Document doc)
{
// do some validation
// ..
// create entity object....direct mapping, automapper, whatever
DocEntity entity = new DocEntity()
entity.Name = doc.Name;
// etc
using (var db = new DbEntities())
{
_repository.Insert(db, doc);
_repository.AddSource(db, entity, doc.Sheet.SourceId);
db.SaveChanges();
}
}
public void AttachFileToDocument(int documentId, string filepath)
{
using (var context = new DbEntities())
{
DocEntity doc = _repository.GetById(context, id);
// validation etc
using (var tran = context.Database.BeginTransaction())
{
try
{
// ..
// determine filename
// copy file
// update pointer to file in doc database
// ..
// save changes
context.SaveChanges();
tran.Commit();
}
catch (System.Exception)
{
tran.Rollback();
throw;
}
}
}
}
}
这是两个不同的东西,所以他们有自己的方法。但是,有时(但不是全部)它们都是必需的并且需要是原子的。我试图创建一个新的服务方法,将这些包装在一个事务中,但它不会回滚 db create。
我还能如何使用相同的通用设计模式来实现这一点 - 或者在这种情况下这不是一个很好的模式 - 每个业务事务一个上下文?
【问题讨论】:
-
我只想扩展 CreateDocument 方法。让它包含 0 个或多个文件。
标签: c# transactions repository-pattern service-layer