1

我正在尝试在 WebApi 项目(不是 asp.net Core)中使用 FluentValidation。

我有以下代码:

public static class UnityConfig
{
    public static void RegisterComponents(UnityContainer container)
    {
        // Register validators
        RegisterValidators(container);

        // Mediatr
        container.RegisterType<IMediator, Mediator>();
        container.RegisterTypes(AllClasses.FromAssemblies(true, Assembly.GetExecutingAssembly()), WithMappings.FromAllInterfaces, GetName, GetLifetimeManager);

        container.RegisterInstance<SingleInstanceFactory>(t => container.Resolve(t));
        container.RegisterInstance<MultiInstanceFactory>(t => container.ResolveAll(t));

        // Automapper profiles
        var profileTypes = typeof(BaseProfile).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(BaseProfile)));
        var config = new MapperConfiguration(cfg => new MapperConfiguration(x =>
        {
            foreach (var type in profileTypes)
            {
                var profile = (BaseProfile)Activator.CreateInstance(type);
                cfg.AddProfile(profile);
            }
        }));

        container.RegisterInstance<IConfigurationProvider>(config);

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }        

    static LifetimeManager GetLifetimeManager(Type type)
    {
        return IsNotificationHandler(type) ? new ContainerControlledLifetimeManager() : null;
    }

    static string GetName(Type type)
    {
        return IsNotificationHandler(type) ? string.Format("HandlerFor" + type.Name) : string.Empty;
    }

    private static void RegisterValidators(IUnityContainer container)
    {
        var validators = AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly());
        validators.ForEach(validator => container.RegisterType(validator.InterfaceType, validator.ValidatorType));
    }
}

我正在扫描程序集并注册验证器,其中现在只有一个,它位于此处:(不要介意奇怪的验证,我正试图让它失败)

public class Query : IRequest<Result>
    {
        public Guid? Id { get; set; }
    }

    public class QueryValidator : AbstractValidator<Query>
    {
        public QueryValidator()
        {
            RuleFor(q => q.Id).Empty();
            RuleFor(q => q.Id).Equal(Guid.NewGuid());
        }
    }

我的 Application_start 看起来像这样:

protected void Application_Start()
    {
        var container = new UnityContainer();
        UnityConfig.RegisterComponents(container);

        GlobalConfiguration.Configure(WebApiConfig.Register);            

        var factory = new UnityValidatorFactory2(GlobalConfiguration.Configuration);

        FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration, x => x.ValidatorFactory = factory);
    }

我有以下验证器工厂:

public class UnityValidatorFactory2 : ValidatorFactoryBase
{
    private readonly HttpConfiguration _configuration;

    public UnityValidatorFactory2(HttpConfiguration configuration)
    {
        _configuration = configuration;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        var validator = _configuration.DependencyResolver.GetService(validatorType) as IValidator;

        return validator;
    }
}

现在; 当我在控制器上调用操作时,“CreateInstance”尝试解析类型的验证器类型:

IValidator<Guid>

代替:

IValidator<Query>

当然什么也没找到,这意味着我的验证没有运行。

有没有人知道为什么会这样?看起来很简单,所以我很难看出哪里出了问题。

4

1 回答 1

0

After having slept on it, I found the answer myself.

I was posting a Guid to my controller instead of the model I was trying to validate (which only contains a guid)

After posting the right model, it now validates correctly.

于 2016-11-10T08:32:58.530 回答