它正在工作,但不是动态的as CustomRepository<ApplicationUser>:
public class CheckUnique : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Type genericClass = typeof(CustomRepository<>).MakeGenericType(typeof(ApplicationUser));
var xx = validationContext.GetService(genericClass) as CustomRepository<ApplicationUser>;
var res = xx.IsValid(value, "username");
if (!res)
{
return new ValidationResult("exist", new[] { "name" });
}
else
{
return null;
}
}
}
我想as CustomRepository<ApplicationUser>使用反射或其他方式将其更改为某些。如果不是,我应该使用许多不同的验证来检查唯一值..
当我尝试使用:
MethodInfo method = genericClass.GetMethod("IsValid");
object params = new object [] { value, "username" };
object val = method.Invoke(this, params );
我收到错误 - 对象与目标类型不匹配,不明白为什么。
一些来自CustomRepository.cs
public class CustomRepository<T> where T : class
{
private readonly AppDbContext _appDbContext;
public CustomRepository(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public bool IsValid(object value, string prop)
{
business logic...
}
}
在启动.cs
services.AddScoped(typeof(CustomRepository<>));
芜湖不芜
相关分类