5

我正在尝试将域驱动设计与测试驱动开发相结合,用于我在 ASP.NET MVC 3 中构建的这个应用程序。我的架构设置有存储库、域模型、视图模型、控制器和视图。所有验证都将在视图模型中处理。我将视图模型设置为从“IValidatableObject”继承,这样当我的控制器方法调用“ModelState.IsValid”时,我的验证属性和我在“Validate”方法中设置的自定义验证都会执行。我遇到的问题是在我的视图模型的 Validate 方法中访问我的存储库。我需要访问存储库以检查数据库中的重复记录。似乎最好的主意是创建一个 IRepository 类型的属性,并通过将我的存储库注入到视图模型的构造函数中来设置该属性。例如:

public class UserViewModel : IValidatableObject
{
       public UserViewModel(User user, IUserRepository userRepository)
       {
              FirstName = user.FirstName;
              LastName = user.LastName;
              UserRepository = userRepository;
              UserName = user.UserName;
       }
       public string UserName { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public IUserRepository UserRepository { get; set; }
       public IEnumerable<ValidationResult> Validate()
       {
           UserCriteria criteria = new UserCriteria { UserName = this.UserName };
           IList<User> users = UserRepository.SearchUsers(criteria);

           if (users != null && users.count() > 0)
           {
               yield return new ValidationResult("User with username " + this.UserName + " already exists."
           }
       }
}

大家觉得这是个好主意吗?

4

2 回答 2

2

这已经足够了,但如果我是你,我会用

...
private readonly Func<IUserRepository> userRepositoryFactory;
...
public IEnumerable<ValidationResult> Validate()  
   {  
       UserCriteria criteria = new UserCriteria { UserName = this.UserName };  
       using(var UserRepository = userRepositoryFactory())
       {
           IList<User> users = UserRepository.SearchUsers(criteria);  

           if (users != null && users.count() > 0)  
           {  
               yield return new ValidationResult("User with username " + this.UserName + " already exists."  
           }  
       }
   }
于 2012-09-28T18:54:15.587 回答
0

您可以添加域服务类以获取与您的条件匹配的对象并在域服务级别进行验证

 public class PurchaseOrder
    {
        public string Id { get; private set; }
        public string PONumber { get; private set; }
        public string Description { get; private set; }
        public decimal Total { get; private set; }
        public DateTime SubmissionDate { get; private set; }
        public ICollection<Invoice> Invoices { get; private set; }

        public decimal InvoiceTotal
        {
            get { return this.Invoices.Select(x => x.Amount).Sum(); }
        }

    }

    public class PurchaseOrderService
    {
        public PurchaseOrderService(IPurchaseOrderRepository repository)
        {
            this.repository = repository;
        }

        readonly IPurchaseOrderRepository repository;

        public void CheckPurchasedOrderExsist(string purchaseOrderId)
        {
                var purchaseOrder = this.repository.Get(purchaseOrderId);
                if (purchaseOrder != null)
                    throw new Exception("PO already exist!");
        }
    }
于 2012-09-28T19:25:29.637 回答