我用以下方法创建了几个中等规模的应用程序,并且晚上睡得很好 ;-)
实体 <=> 服务 <=> 模型
请注意,这3个层必须由包/模块/程序集分离,并且仅限于后端。
实体: 领域层,领域对象,存储库,数据库模型,数据对象层(DAL)
服务: 业务逻辑层(BLL),业务服务层
模型: 数据传输对象(DTO),演示层,视图模型(请从您的字典中删除演示/视图)
视图是一个单独的项目(PWA,渐进式Web应用程序),它使用API并且不需要任何后端代码支持。它有自己的视图模型和业务逻辑。
例如:
MyProject.Entities (DAL):
[Table("customers")]
public class Customer
{
protected Customer() { }
public Customer(string name) : this()
{
Id = IdGenerator.Next();
SetName(name);
}
[Key]
public virtual string Id { get; protected set; }
public virtual string Name { get; protected set; }
[Column("summary")]
public virtual string Description { get; set; }
public void SetName(string name)
{
if (string.IsNullOrEmpty())
throw new ArgumentNullException(nameof(name));
Name = name;
}
}
我的项目.模型(数据传输对象):
public class IdModel
{
[Required]
public string Id { get; set; }
}
public class CreateCustomerModel
{
[Required]
[MaxLength(50)]
public string Name { get; set; }
}
public class EditCustomerModel : IdModel
{
[Required]
[MaxLength(50)]
public string Name { get; set; }
public string Description { get; set; }
}
我的项目.Services (BLL):
public class CustomerService
{
private readonly DbContext _db;
private readonly IMapper _mapper;
public CustomerService(DbContext db, IMapper mapper)
{
_db = db;
_mapper = mapper;
}
public async Task<EditCustomerModel> Get(IdModel model)
{
var customer = await _db.Get<Customer>(model.Id);
return _mapper.Map<EditCustomerModel>(customer);
}
public async Task<IdModel> Create(CreateCustomerModel model)
{
var customer = new Customer(model.Name);
await _db.SaveOrUpdate(customer);
return _mapper.Map<IdModel>(customer);
}
public async Task Edit(EditCustomerModel model)
{
var customer = await _db.Get<Customer>(model.Id);
customer.SetName(model.Name);
customer.Description = model.Description;
await _db.SaveOrUpdate(customer);
}
public async Task Delete(IdModel model)
{
await _db.Remove<Customer>(model.Id);
}
}
上面的例子只是一个简单的CRUD服务。但是同样的方式,您可以实现任何领域服务,例如CustomerInvoiceService
:
[Description("Creates a new customer and invoices it. Returns invoice Id.")]
public async Task<IdModel> CreateCustomerAndInvoiceIt(CreateCustomerInvoiceModel model)
{
model.InvoiceForm.CustomerId = await _customerService.Create(model.CustomerForm);
var invoiceId = await _invoiceService.Create(model.InvoiceForm);
return invoiceId;
}
只需公开 API/服务,让前端开发人员完全独立于后端进行工作。如果是桌面应用程序或前端使用后端语言(如C#/Java/Go),他们必须构建自己的“前端逻辑层和模型”,并且在任何情况下都不能允许将“域/业务层”与“表示层”混合在一起。前端是完全分离的东西,正如有人上面提到的 视图,我建议从BLL字典中完全删除该单词。
我的观点。