1

这专门用于Project Silk中 DDD 的参考用法。

该项目使用 DDD 并实现了HandlersServices的概念。这两种类型的区别和用例到底是什么?

例如,有一个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);
            }
        }
    }
4

1 回答 1

0

在您的示例中,我认为区别在于用户的创建是用户的主动行为,而 viecle 的创建是被动的。有人提交一个表单来创建一个用户,另一方面,它在完成一些操作后触发创建一个viecle(可能是在创建用户之后?)。

也许你会对这个答案感兴趣。

于 2013-08-20T00:58:53.227 回答