Best method for implementing .Must() with repository?

Dec 18, 2009 at 4:38 PM
Edited Dec 30, 2009 at 10:10 PM

EDIT: I just realized this doesn't even belong here. This is a question about FluentValidation not xVal. Sorry...

I'm trying to implement some logic behind ensuring that a field on an object is unique, say the title of an Account Status ("Open," "Closed," etc.).

Using the examples put forward I have a static method in my AccountStatusViewModelValidator class:

public static bool HaveAUniqueTitle(String title)
{
 IRepository<AccountStatus> db = new Repository<AccountStatus>();
 IDictionary<string, object> propertyValues = new Dictionary<string, object>();
 propertyValues.Add("Title", title);
 if (db.FindOne(propertyValues) != null)
  return false;
 else
  return true;
}

And I've implemented the rule accordingly:

public AccountStatusViewModelValidator()
{
 RuleFor(at => at.Title)
  .Cascade().StopOnFirstFailure()
  .NotEmpty()
  .Length(1, 50)
  .Must(HaveAUniqueTitle).WithMessage("This Account Status has already been defined.");
}

However, I really don't like the fact that I'm instantiating my repository directly and would rather use dependency injection/IoC to inject that repository:

public static bool HaveAUniqueTitle(String title, IRepository<AccountStatus>)
{
 IDictionary<string, object> propertyValues = new Dictionary<string, object>();
 propertyValues.Add("Title", title);
 if (db.FindOne(propertyValues) != null)
  return false;
 else
  return true;
}

Further, I'd like to extract the HaveAUniqueTitle() method into an extension or separate class via the Strategy Pattern or something similar since it will be the same each time I use it.

Does anyone have some architectural input here on how to do this sort of thing?

I suppose I could inject the repository at the AccountStatusViewModelValidator ctor but that doesn't help if I want to abstract the method into a separate class.

The real motivation is the HaveAUniqueTitle() method should be made Generic and refactored to a method using injection that is reused instead of having a cut-and-paste HaveAUniqueTitle method with specific repository instantiation in each ViewModelValidator class that uses this business rule.

PS. The HaveAUniqueTitle() method is static so I can use it in client-side validation a-la xVal 1.0.

Cheers,

-devon