Validation without ServiceLocator
Posted
by Dmitriy Nagirnyak
on Stack Overflow
See other posts from Stack Overflow
or by Dmitriy Nagirnyak
Published on 2010-05-10T23:41:25Z
Indexed on
2010/05/10
23:44 UTC
Read the original article
Hit count: 456
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 S*ervice 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.
So the question would be: is there any way to use DI/IoC for the situation described above?
Thanks,
Dmitriy.
© Stack Overflow or respective owner