这个问题与技术无关,但我正在使用 C# 和 ASP.NET,并将其用于伪代码。哪种方法更好,为什么?
protected void Page_Load(object sender, EventArgs e) {
SomeBusinessClass.SomeBusinessMethod();
}
public class SomeBusinessClass {
public void SomeBusinessMethod() {
using (TransactionScope ts = new TransactionScope()) {
doStuff();
ts.Complete();
}
catch (Exception ex) {
LogError("An error occured while saving the order", ex);
}
}
}
}
protected void Page_Load(object sender, EventArgs e) {
using (TransactionScope ts = new TransactionScope()) {
try {
SomeBusinessClass.SomeBusinessMethod();
ts.Complete();
}
catch (Exception ex) {
LogError("An error occured while saving the order", ex);
}
}
}
public class SomeBusinessClass {
public void SomeBusinessMethod() {
doStuff();
}
}
我担心通过在我的业务逻辑代码中引入对日志记录、事务等的依赖,我会降低它的通用性。另一方面,UI 代码看起来更简洁。我打不通电话。让我知道我应该考虑哪些其他因素。
最佳答案
事务 :您的业务层的核心问题,因此它绝对应该处理这个问题(尽管您可以通过 a unit of work implementation 集中事务处理)。
更新:我不再同意这部分。通常, Controller 、演示者或其他顶级调用者是处理事务的最佳位置(如 the onion architecture )——在许多情况下,这是定义逻辑工作单元的地方。
异常处理 :在每一层中根据需要使用 - 但仅在业务层 when you can actually do something about it 中使用它(不仅仅是记录它)。如果您的基础架构支持,请在 UI 层使用全局处理程序。
日志记录 :在任何需要它的层中使用跟踪或信息日志记录,仅在顶层记录异常。
关于c# - 设计问题 - 业务层方法的原子性应该如何?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1765256/