Hi,
I am getting back again and again to it thinking about the best way to perform validation on POCO objects that need access to some context (ISession in NH, IRepository for example).
The only option I still can see is to use Service Locator, so my validation would look like:
public User : ICanValidate {
public User() {} // We need this constructor (so no context known)
public virtual string Username { get; set; }
public IEnumerable<ValidationError> Validate() {
if (ServiceLocator.GetService<IUserRepository>().FindUserByUsername(Username) != null)
yield return new ValidationError("Username", "User already exists.")
}
}
I already use Inversion Of control and Dependency Injection and really don't like the ServiceLocator due to number of facts:
- Harder to maintain implicit dependencies.
- Harder to test the code.
- Potential threading issues.
- Explicit dependency only on the ServiceLocator.
- The code becomes harder to understand.
- Need to register the ServiceLocator interfaces during the testing.
But on the other side, with plain POCO objects, I do not see any other way of performing the validation like above without ServiceLocator and only using IoC/DI.
Currently I perform such kind of validation in the service layer. So whenever an actor tries to change username (might be of course something different) the service performs this validation. One obvious disadvantage is that every service using the User must perform this check (even if it is one call).
So the question would be: is there any way to use DI/IoC for the situation described above?
Thanks,
Dmitriy.