I am trying to use a combination of Domain Driven Design with Test Driven Development for this application that I create in ASP.NET MVC 3. My architect is configured using repositories, domain models, models, controllers and views. All checks will be processed in the view model. I set my view model to inherit from "IValidatableObject" so that my validation attributes and my custom validation that I set in the "Validate" method are executed when my controller method calls "ModelState.IsValid". The problem I am facing is accessing my repository in the Validate method of my view model. I need to access the repository to check for duplicate entries in the database. Seem to be,that the best idea would be to create a property of type IRepository and set this property by passing my repository to the view model constructor. For instance:
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."
}
}
}
, , , ?