我要註冊的通用驗證(流利驗證)與SimpleInjector ...註冊通用驗證用簡單的注射器
這裏是我試過到目前爲止:
User.cs:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
UserService.cs
public class UserService : IUserService
{
private readonly IValidator<User> _userValidator;
public UserService(IValidator<User> userValidator)
{
_userValidator = userValidator;
}
public OperationResult Add(User user)
{
OperationResult operationResult = new OperationResult();
ValidationResult validationResult = _userValidator.Validate(user);
if (!validationResult.IsValid)
{
operationResult.IsSuccess = false;
ValidationFailure firstOrDefaultValidationFailure =
validationResult.Errors.FirstOrDefault();
if (firstOrDefaultValidationFailure != null)
{
operationResult.Message = firstOrDefaultValidationFailure.ErrorMessage;
}
}
//TODO do your business here...
return operationResult;
}
}
IOC:
Container = new Container();
// I WANT TO MAKE BELOW LINE GENERIC...
Container.Register(typeof(IValidator<User>),() => new UserValidator());
Container.Register<IUserService, UserService>(Lifestyle.Transient);
Container.Verify();
它的工作現在。但正如你所看到的,驗證者的註冊不是通用的。
我試過了;
Container.Register(typeof(IValidator<>), typeof(ValidationContext<>));
它給錯誤運行時:
For the container to be able to create
ValidationContext<T>
it should have only one public constructor: it has 2
我也試過:
Container.Register(typeof(IValidator<>), typeof(ValidatorDescriptor<>));
另一個錯誤:
The supplied type
ValidatorDescriptor<T>
does not implementIValidator<T>
最後我想:
IValidatorFactory validatorFactory = new AttributedValidatorFactory();
IValidator<User> validator = validatorFactory.GetValidator<User>();
但它提供了空驗證器。因爲在User.cs類中沒有任何屬性,例如;
[Validator(typeof(UserValidator))]
我該怎麼做才能解決這個問題?