我需要替换以下行:
var validator = DependencyResolver.Current.GetService<IValidator<T>>();
在
public class ValidationFactory : IValidationFactory
{
public void Validate<T>(T entity) where T : class, IEntity
{
var validator = DependencyResolver.Current.GetService<IValidator<T>>();
var result = validator.Validate(entity);
if (result.Count() > 0)
throw new BusinessServicesException(result);
}
}
我需要参考: System.Web.Mvc 才能使其工作。
是否有任何其他解决方案可以使用统一挂钩正确的验证器?
接口
public interface IValidator<T> where T : class, IEntity
{
IEnumerable<ValidationResult> Validate(T entity);
}
public interface IValidationFactory
{
void Validate<T>(T entity) where T : class, IEntity;
}
一个特定的验证器:
public class CanCreateOrUpdateUserValidator : IValidator<User>
{
private readonly IUnitOfWork unitOfWork;
public CanCreateOrUpdateUserValidator(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public IEnumerable<ValidationResult> Validate(User entity)
{
if (entity == null)
{
yield return new ValidationResult("");
}
else
{
// more logic
}
}
}
统一注册:
container.RegisterType<IValidationFactory, ValidationFactory>(new ContainerControlledLifetimeManager());
container.RegisterType<IValidator<User>, CanCreateOrUpdateUserValidator>(new ContainerControlledLifetimeManager());
最好的祝福