C# fluent validation of interface underlaying object

Viewed 558

I got an azure function, I receive a Json the json contains

List<Iinterface> objects {get;set;}

then I can have several object implementing Iinterface

public class A : Iinterface { ... }

The json converter actually resolves the types, so on a list's item if I invoke .GetType i get the correct underlaying type!

But then I need to validate according to the underlaying type!

I got this, but can I do it better?

public class IinterfaceValidator : AbstractValidator<Iinterface>
    {
        public IinterfaceValidator (AValidator aValidator)
        {
            When(x => x.GetType() == typeof(A), () =>
            {
                RuleFor(x => (A)x)
                    .SetValidator(aValidator);
            });
        }
    }
1 Answers

A little cleaner implementation would be to use SetInheritanceValidator. Suppose you have validators AValidator and BValidator for below classes respectively.

public class A : Iinterface { ... }

public class B : Iinterface { ... }

Then you define a validator for Iinterface like below. Note I am using lazy initialization of child validators to avoid creation of instance during initialization.

public class IinterfaceValidator : AbstractValidator<Iinterface> 
{
    public IinterfaceValidator() {
        RuleFor(x => x).SetInheritanceValidator(v => {
            v.Add<A>(i => new AValidator())
             .Add<B>(i => new BValidator());
        });
    }
}

You can also have a look at their inheritance example here.

Related