I am using FluentValidator in a C# project. I would like to make a generic method that can validate data from 2 possible types:
public class MyClassAValidator : AbstractValidator<MyClassA> {...}
public class MyClassBValidator : AbstractValidator<MyClassB> {...}
public void MyMt<T>(T param)
{
AbstractValidator<T> validator = null;
if(param is MyClassA)
{
var validator = new MyClassAValidator(); // Generatescompiler error
}
else if (cCOSLDto is CCOSLLoyerDto)
{
validator = new MyClassBValidator(); // Generatescompiler error
}
ValidationResult result = validator.Validate(param);
}
Compiler cannot convert MyClassAValidator() or MyClassBValidator() to AbstractValidator
How can I handle this? I suspect (just a suspicion though) that it would work if I set a base class to MyClassA and MyClassB. But I would like to avoid this if possible as MyClassA and MyClassB are actually DTO classes so I would prefer them to stay without inheritence relationship.
CodePudding user response:
Actually, if you need to validate two different types of objects in one method, you dont have to mess with inheritance from a generic class.
There is an easy way to do this. Any Validate
method returns ValidationResult
, so you can use something like this:
using FluentValidation;
using FluentValidation.Results;
using System;
namespace FluentValidatorTranslation
{
class Program
{
static void Main(string[] args)
{
}
public ValidationResult MyMt<T>(T param)
{
ValidationResult result;
if(param is MyClassA myClassA)
{
var validator = new MyClassAValidator();
result = validator.Validate(myClassA);
}
else if (param is MyClassB myClassB)
{
var validator = new MyClassBValidator();
result = validator.Validate(myClassB);
}
else
{
throw new ArgumentException("Type not supported");
}
return result;
}
}
public class MyClassA { }
public class MyClassB { }
public class MyClassAValidator : AbstractValidator<MyClassA>
{
}
public class MyClassBValidator : AbstractValidator<MyClassB>
{
}
}