这专门用于Project Silk中 DDD 的参考用法。
该项目使用 DDD 并实现了Handlers和Services的概念。这两种类型的区别和用例到底是什么?
例如,有一个UserServices
创建用户的服务。但是车辆的创建是在处理程序中完成的。
想知道这个决定背后的原因。
域\用户服务
public class UserServices : IUserServices
{
private readonly IUserRepository userRepository;
public UserServices(IUserRepository userRepository)
{
if (userRepository == null)
throw new ArgumentNullException("userRepository");
this.userRepository = userRepository;
}
public User CreateUser(User newUser)
{
if (newUser == null) throw new ArgumentNullException("newUser");
try
{
Model.User userToAdd = ToDataModelUser(newUser);
this.userRepository.Create(userToAdd);
return ToServiceUser(userToAdd);
}
catch (InvalidOperationException ex)
{
throw new BusinessServicesException
(Resources.UnableToCreateUserExceptionMessage, ex);
}
}
}
域\处理程序\CreateVehicle.cs
public class CreateVehicle
{
private readonly IVehicleRepository _vehicleRepository;
private readonly IVehiclePhotoRepository _photoRepository;
public CreateVehicle(IVehicleRepository vehicleRepository,
IVehiclePhotoRepository photoRepository)
{
_vehicleRepository = vehicleRepository;
_photoRepository = photoRepository;
}
public virtual void Execute(int userId,
ICreateVehicleCommand vehicleForm,
HttpPostedFileBase photoFile)
{
if (vehicleForm == null) throw
new ArgumentNullException("vehicleForm");
try
{
var vehicle = vehicleForm.ConvertToEntity(userId);
_vehicleRepository.Create(userId, vehicle);
if (photoFile == null) return;
// the double reference between vehicle and photo
//is a potential source of pain
var photo = photoFile.ConvertToEntity();
_photoRepository.Create(vehicle.VehicleId, photo);
vehicle.PhotoId = photo.VehiclePhotoId;
_vehicleRepository.Update(vehicle);
}
catch (InvalidOperationException ex)
{
throw new BusinessServicesException
(Resources.UnableToCreateVehicleExceptionMessage, ex);
}
}
}