开发者

How do I validate a property that needs to access a repository in xVal?

I'm trying to use xVal to validate the registration of a new user. I've ran into a buzz saw when trying to implement the logic that checks to see if the user name that the new user is trying to reg开发者_如何学Cister with is already taken. I can't seem to find a way to accomplish this without having my User entity have a dependence on my UsersRepository. Here's the method I need to find a way to implement in the my User Entity:

public IEnumerable<ErrorInfo> ValidateUniqueUserName(string username)
{
    if(usersRepository.Users.Exists(m => (m.UserName == username)))
        yield return new ErrorInfo("UserName", "User name already exists");
}

Any ideas on how I can continue to use xVal for this scenario and keep my User entity decoupled from my UsersRepository?


DDD would suggest that you might have a Domain Service to abstract the Users repo from the domain validation (invariant enforcing).

I'd like to know where the code from your example above resides (validation service)? But i'd suggest you make sure it is in the domain. Here is a clever way to attach complex validation to entities that still support the IDataErrorInfo interface.

What i would suggest is an Domain Service within your validation method that returns your Users.Exists query. Something like:

        base.AddRule(new ValidationRule()
        {
            Properties = "username",
            Description = "User name already exists",
            validator = () => !(new UserService()).Users.Exists(m => (m.UserName == username))
        });

In the example above i will be using DI to inject the appropriate dependencies into the UserService for accessing of the repo/data but you could use a factory or manual DI object creation method if you like:

        base.AddRule(new ValidationRule()
        {
            Properties = "username",
            Description = "User name already exists",
            validator = () =>
                {
                    UserService us = ObjectFactory.GetInstance<UserService>();
                    return !us.Users.Exists(m => (m.UserName == username));
                }
        });

NOTE: The above method requires the validator property to be set to false to indicate an invalid state (in case that wasn't clear).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜