关于窗口和基于Web的应用程序的业务逻辑层设计的意见
-
05-10-2019 - |
题
我需要一些意见来选择我的基于Web的业务层功能的哪些签名:
函数void createuser(公司USERCOMPANY,字符串名称...)
或者
函数void createuser(int companiD,字符串名称...)
如果这是一个基于窗口的,我会选择功能来采用对象而不是int,因为因为公司已经加载到窗口表单上,所以为什么不使用它。另外,我认为业务层应采用业务对象,并且它是安全的(防止不小心通过0或-1)。
但另一方面,如果这是基于Web的应用程序,则仅将ID加载到客户端站点。因此,加载公司对象是多余的,因为无论如何,最终只能保存在dabasebase中。
希望我的描述不会太困惑= P谢谢您的阅读。
解决方案
我认为您回答了自己的问题,这取决于您正在使用的演示层。但是,当您想保持此业务层通用时,您必须使用ID。
这是另一个想法。我个人喜欢将所有突变包含在课堂上,我称之为命令。例如,您可以有一个 CreateUserCommand
从基本命令继承。这将允许您这样使用它(我在这里假设C#):
var command = new CreateUserCommand();
command.UserCompanyId = companyId;
command.UserName = name;
command.Execute();
将此逻辑包裹在命令中时,非常好。它允许您将单个用例放入一个命令中。尤其是当命令中的逻辑数量增长时,您会欣赏这种模式,但我发现它对Crud操作也非常有效。
这种模式还使您可以在基类中抽象交易模型。基类可以在数据库事务中包装呼叫以执行。这是一个简单的实现:
public abstract class CommandBase
{
public void Execute()
{
this.Validate();
using (var conn = ContextFactory.CreateConnection())
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
using (var db = ContextFactory.CreateContext(conn))
{
this.ExecuteInternal(db);
db.SubmitChanges();
}
transaction.Commit();
}
}
}
protected virtual void Validate() { }
protected abstract void ExecuteInternal(YourDataContext context);
}
这就是 CreateUserCommand
看起来像:
public class CreateUserCommand : CommandBase
{
public int UserCompanyId { get; set; }
public string UserName { get; set; }
protected override void ExecuteInternal(YourDataContext context)
{
this.InsertNewUserInDatabase(context);
this.ReportCreationOfNewUser();
}
protected override void Validate()
{
if (this.UserCompanyId <= 0)
throw new InvalidOperationException("Invalid CompanyId");
if (string.IsNullOrEmpty(this.UserName))
throw new InvalidOperationException("Invalid UserName");
}
private void InsertNewUserInDatabase(YourDataContext context)
{
db.Users.InsertOnSubmit(new User()
{
Name = this.UserName,
CompanyId = this.CompanyId
});
}
private void ReportCreationOfNewUser()
{
var message = new MailMessage();
message.To = Configuration.AdministratorMailAddress;
message.Body = "User " + this.Name + " was created.";
new SmtpClient().Send(message);
}
}
我希望这有帮助。
不隶属于 StackOverflow