0

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?

2
  • Is the real question what happens if you use opt.IncludeRuleSets(...) with an unrelated type? FooItem and BarItem have no inheritance relation. Neither do FooItemValidator and BarItemValidator. You'll get a runtime cast error at some point Commented Dec 18, 2024 at 13:14
  • ..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 Commented Dec 18, 2024 at 13:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.