I have several business rules for my FormPartB object that depend on related entities Licensee and FormPartA. I’m new to FluentValidation.
What (I think) I want to do is:
-
Within my
FormPartBValidator, get theLicenseeandFormPartAentities once, then set up a bunch of rules (i.e.Must()predicates) forFormPartBusing values from those related objects. -
i.e. I dont want to fetch both external entities again within each rule defintion.
I had a couple of thoughts:
(1) Get those entities in the Validator’s constructor, above my RuleFor definitions, then save those entities as private fields,
public PartBValidator()
{
// Get my external data and save as private fields
RuleFor...
RuleFor...
}
or
(2) Get those entities within the call to Validate() then save those entities as private fields:
public override ValidationResult Validate(FormPartB instance)
{
// Get my external data and save as private fields
return base.Validate(instance);
}
However
-
In option (1) I can’t seem to access the FormPartB instance
-
In option (2) Validate() doesnt seem to be working the way I thought it would (i.e. doesnt seem to get called on every validation of
FormPartB.) -
And I’m not even sure that “get objects and save as private fields” is the right way to go.
Any advice?
I’ve handled this in applications by dependency-injecting a service into the constructor that retrieves the data that validation is dependent on, and it’s worked out quite nicely.
Here’s an example:
If you’re concerned about the performance impact of grabbing that data via the service within the rule definition, you could consider some caching options as well.