I learned from here that cast cannot be done with the type variable.
I use fluent validation for entity validation in my project, and for this I wrote an aspect using postsharp. But I got stuck somewhere. In the constructor method of my aspect class, I get the type of my validation class. In the Entry method, I dynamically create an example of this class and cast to IValidator. But since I cast to IValidator, I cannot pass the ruleset parameter to the Validate method. I need to cast IValidator . This is also impossible. How should I go about this problem? I hope I could tell. I add the codes below for the example . Thanks.
[PSerializable]
public class FluentValidationAspect : OnMethodBoundaryAspect
{
private readonly Type _validatorType;
private readonly string _ruleSet;
public FluentValidationAspect(Type validatorType, string ruleSet = null)
{
_validatorType = validatorType;
_ruleSet = ruleSet;
}
public override void OnEntry(MethodExecutionArgs args)
{
var entityType = _validatorType.BaseType?.GetGenericArguments()[0];
var entities = args.Arguments.Where(x => x.GetType() == entityType);
if (string.IsNullOrEmpty(_ruleSet))
{
var validator = (IValidator)Activator.CreateInstance(_validatorType);
foreach (var entity in entities)
ValidatorTool.FluentValidate(validator, entity);
}
else
{
var validator = (IValidator<entityType>)Activator.CreateInstance(_validatorType);
foreach (var entity in entities)
ValidatorTool.FluentValidate<entityType>(validator, entity);
}
}
}
public static class ValidatorTool
{
public static void FluentValidate(IValidator validator, object entity)
{
var result = validator.Validate(entity);
if (result.Errors.Any())
throw new ValidationException(result.Errors);
}
public static void FluentValidate<T>(IValidator<T> validator, T entity, string ruleSet) where T : class, new()
{
var result = validator.Validate(entity, ruleSet: ruleSet);
if (result.Errors.Any())
throw new ValidationException(result.Errors);
}
}