/// <summary>
/// Customer数据转输对象抽象类,放Customer通过属性
/// </summary>
public abstract class CustomerCommand : Command
{
public Guid Id { get; protected set; }
public string Name { get; protected set; }
public string Email { get; protected set; }
public DateTime BirthDate { get; protected set; }
}
/// <summary>
/// Customer注册命令消息参数
/// </summary>
public class RegisterNewCustomerCommand : CustomerCommand
{
public RegisterNewCustomerCommand(string name, string email, DateTime birthDate)
{
Name = name;
Email = email;
BirthDate = birthDate;
}
/// <summary>
/// 命令信息参数验证
/// </summary>
/// <returns></returns>
public override bool IsValid()
{
ValidationResult = new RegisterNewCustomerCommandValidation().Validate(this);
return ValidationResult.IsValid;
}
}
/// <summary>
/// 新增
/// </summary>
/// <param name="customerViewModel">视图模型</param>
public void Register(CustomerViewModel customerViewModel)
{
//将视图模型 映射到 RegisterNewCustomerCommand 新增命令实体
var registerCommand = _mapper.Map<RegisterNewCustomerCommand>(customerViewModel);
Bus.SendCommand(registerCommand);
}
/// <summary>
/// Customer注册命令处理
/// </summary>
/// <param name="message"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task<bool> Handle(RegisterNewCustomerCommand message, CancellationToken cancellationToken)
{
//对实体属性进行验证
if (!message.IsValid())
{
NotifyValidationErrors(message);
return Task.FromResult(false);
}
//将命令消息转成领域实体
var customer = new Customer(Guid.NewGuid(), message.Name, message.Email, message.BirthDate);
//如果注册用户邮件已存在,发起一个事件
if (_customerRepository.GetByEmail(customer.Email) != null)
{
Bus.RaiseEvent(new DomainNotification(message.MessageType, "The customer e-mail has already been taken."));
return Task.FromResult(false);
}
//由Equinox.Infra.Data.Repository来实现数据持久化。事件是过去在系统中发生的事情。该事件通常是命令的结果.
_customerRepository.Add(customer);
//新增成功后,使用事件记录这次命令。
if (Commit())
{
Bus.RaiseEvent(new CustomerRegisteredEvent(customer.Id, customer.Name, customer.Email, customer.BirthDate));
}
return Task.FromResult(true);
}