I am using Asp.net Core with AutoFac and follow the answers accepted here:
Validation: how to enter model state wrapper using Ninject?
In this case, ninject is used. I do not understand how to make the equivalent of this ninject part in autoFac, in particular kernel.Get :
Func<Type, IValidator> validatorFactory = type => { var valType = typeof(Validator<>).MakeGenericType(type); return (IValidator)kernel.Get(valType); }; kernel.Bind<IValidationProvider>() .ToConstant(new ValidationProvider(validatorFactory));
Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services) { var containerBuilder = new ContainerBuilder(); IValidator ValidatorFactory(Type type) { var valType = typeof(Validator<>).MakeGenericType(type);
The problem is that the container is only available after using .Build() , so I donβt see how to do it. Is it necessary to register this service after calling .Build() and then calling .Build() again, or is this .Resolve() wrong use here.
Validation Classes:
internal sealed class ValidationProvider : IValidationProvider { private readonly Func<Type, IValidator> _validatorFactory; public ValidationProvider(Func<Type, IValidator> validatorFactory) { _validatorFactory = validatorFactory; } public void Validate(object entity) { var results = _validatorFactory(entity.GetType()).Validate(entity).ToArray(); if (results.Length > 0) throw new ValidationException(results); } public void ValidateAll(IEnumerable entities) { var results = ( from entity in entities.Cast<object>() let validator = _validatorFactory(entity.GetType()) from result in validator.Validate(entity) select result).ToArray(); if (results.Length > 0) throw new ValidationException(results); } } public abstract class Validator<T> : IValidator { IEnumerable<ValidationResult> IValidator.Validate(object entity) { if (entity == null) throw new ArgumentNullException(nameof(entity)); return Validate((T)entity); } protected abstract IEnumerable<ValidationResult> Validate(T entity); } public class UploadValidator : Validator<AudioModel> { protected override IEnumerable<ValidationResult> Validate(AudioModel model) { if (string.IsNullOrWhiteSpace(model.Name)) { yield return new ValidationResult("Name", "Name is required"); } } }
Martin Dawson Jul 18 '17 at 16:06 2017-07-18 16:06
source share