对于基于xml的存储库,什么是更好的方法:
1)每次调用存储库时保存对基础xml文档的更改...
public class XmlRepository1
{
private XDocument xDocument;
public void CrudOp()
{
// Perform CRUD operation...
// Call Save()
xDocument.Save(path);
}
}
或
2)为最终用户提供SaveChanges()方法......
public class XmlRepository2
{
private XDocument xDocument;
public void CrudOp()
{
// Perform CRUD operation...
// DON'T call save
}
// Provide a SaveChanges() method to the end-user...
public void SaveChanges()
{
xDocument.Save(path);
}
}
我的倾向倾向于选项1,因为提供SaveChanges()方法看起来并不像存储库的责任。但是,由于以下几个原因,我在猜测这个决定:
a)在多线程环境中,如果对存储库的调用失败,最终用户可以轻松地回滚更改,从而使对象处于部分变异状态。
b)选项2提供了“类似批处理”的范例,由于各种原因,我可以看到它更灵活。
答案 0 :(得分:3)
考虑添加某种交易支持(接近您的第二个apporach)。
public class XmlRepository2
{
public void CrudOp()
{
// DON'T call save
}
public MakeTransacedChanges(Action<XmlRepository2> makeChanges)
{
try{
makeChanges(this);
saveChanges();
}
catch (RepositoryException e)
{
//revert changes
}
}
private void saveChanges()
{
xDocument.Save(path);
}
}
答案 1 :(得分:1)
我更喜欢在存储库中使用单独的Save方法,以便在出现问题时还原我的更改。
我发现了这篇文章Repositories and the Save Method。希望它会有所帮助。