XML 存储库;保存()或不保存()
对于基于 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 提供了“类似批处理”的范例,出于多种原因,我认为它更加灵活。
What would be a better approach for an xml-based repository:
1) Save changes to the underlying xml document on each call to the repository...
public class XmlRepository1
{
private XDocument xDocument;
public void CrudOp()
{
// Perform CRUD operation...
// Call Save()
xDocument.Save(path);
}
}
or
2) Provide the end-user with a SaveChanges() method...
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);
}
}
My inclination leans towards option 1, because providing a SaveChanges() method doesn't really seem like a repositories responsibility. However, I'm second-guessing this decision for a couple of reasons:
a) In a multi-threaded environment, this gives the end-user an easy way to roll-back changes should a call to the repository fail, leaving objects in a partially-mutated state.
b) Option 2 provides a "batch-like" paradigm, which I can see as being more flexible for a variety of reasons.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑添加某种事务支持(接近您的第二个方法)。
Consider adding some sort of transaction support (close to your second apporach).
我更喜欢在存储库中使用单独的 Save 方法,以便在出现问题时有机会恢复我的更改。
我找到了这篇文章 存储库和保存方法。希望它会有所帮助。
I prefer to have separate Save method in repository to have a chance to revert my changes if something will go wrong.
I found this article Repositories and the Save Method. Hope it will help.