我只是通过将反射与通用接口相结合来解决我的问题,所以我唯一需要的是为每个实体实现通用接口。
我有一个拦截所有方法的拦截器。它对我有用。但谁能给我一些关于表演的信息?这是进行验证的正确方法吗?拦截器:
public class ValidatorInterceptor : IInterceptor
{
private readonly IServiceFactory factory;
public ValidatorInterceptor(IServiceFactory _factory)
{
factory = _factory;
}
public void Intercept(IInvocation invocation)
{
var methodParameterSet = invocation.InvocationTarget.GetType().GetMethod(invocation.Method.Name).GetParameters().ToList();
for (var index = 0; index < methodParameterSet.Count; index++)
{
var parameter = methodParameterSet[index];
var paramType = parameter.ParameterType;
var customAttributes = new List<object>();
var factoryMethod = factory.GetType().GetMethod("GetService");
var baseValidatorType = typeof(IValidator<>);
var validatorType = baseValidatorType.MakeGenericType(paramType);
factoryMethod = factoryMethod.MakeGenericMethod(validatorType);
var validator = factoryMethod.Invoke(factory, null);
customAttributes.AddRange(parameter.GetCustomAttributes(true).Where(item => item.GetType().Name.StartsWith("Validate")));
foreach (var attr in customAttributes)
{
dynamic attribute = attr;
var method = validator.GetType().GetMethod("Validate");
method = method.MakeGenericMethod(paramType);
object[] parameterSet = {invocation.Arguments[index], attribute.Rule, attribute.IsNullCheck};
method.Invoke(validator, parameterSet);
}
}
invocation.Proceed();
}
}
UserAccount Entity 的 IValidator 的实现是这样的:
public class ValidateUserAccount<T> : IValidator<T> where T : UserAccount
{
public void Validate<T>(T entity, object obj1 = null, object obj2 = null) where T : class
{
var item = (UserAccount) Convert.ChangeType(entity, typeof(UserAccount));
if (item == null)
throw new ArgumentNullException("user account cant be null");
}
}
对于字符串验证器:
public class ValidateString : IValidator<string>
{
public void Validate<T>(T entity, object rukeObj = null, object nullChekcObj = null) where T : class
{
var item = (string) Convert.ChangeType(entity, typeof(string));
var rule = (Regex)Convert.ChangeType(rukeObj, typeof(Regex));
var reqItem = Convert.ChangeType(nullChekcObj, typeof(bool));
var isRequire = reqItem != null && (bool) reqItem;
if (isRequire && string.IsNullOrEmpty(item))
throw new ArgumentException("value can not be null!");
if (!rule.Match(item).Success)
throw new ArgumentException("[" + item + "] is not a valid input!");
}
}