Suppose I have the following domain models in a C# .NET 6 EF Core project:
public abstract class BaseItem
{
// Base class implementation...
}
public class FooItem : BaseItem
{
// Derived Class A implementation...
}
public class BarItem : BaseItem
{
// Derived Class B implementation...
}
And suppose I am using FluentValidation to validate instances of BaseItem:
public class BaseItemValidator : AbstractValidator<BaseItem>
{
public BaseItemValidator()
{
// Rules for Base Item
}
}
public class FooItemValidator : AbstractValidator<FooItem>
{
public FooItemValidator()
{
Include(new BaseItemValidator());
RuleSet("FooRules", () =>
{
// Rules for derived FooItem instances
})
}
}
public class BarItemValidator : AbstractValidator<BarItem>
{
public BarItemValidator()
{
Include(new BaseItemValidator());
}
}
If I have a generic service for BaseItem instances using derived validators (dependency-injected), akin to the following..
public class BarItemService<T>
{
private IValidator<T> _validator;
public BarItemService(IValidator<T> validator)
{
_validator = validator;
}
public async Task AddItem(T item, CancellationToken token = default)
{
var result = await _validator.ValidateAsync(item, opt => opt.IncludeRuleSets("FooRules"), token);
if (!result.IsValid)
{
// Indicate the item is not valid
}
// Rest of the method...
}
}
..will the validator fail if T is BarItem and we try to include the rule set specific to FooItem?
opt.IncludeRuleSets(...)with an unrelated type?FooItemandBarItemhave no inheritance relation. Neither doFooItemValidatorandBarItemValidator. You'll get a runtime cast error at some point..will the validator fail if T is BarItem and we try to include the rule set specific to FooItem?question sounds like you could have simply tested it, or? maybe I have misunderstood it