使用Mediatr和Unity进行FluentValidation

时间:2016-11-09 16:43:29

标签: c# asp.net unity-container fluentvalidation mediatr

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

我有以下代码:

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);
    }

我有以下validatorFactory:

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;
    }
}

现在;当我在控制器上调用动作时,&#39; CreateInstance&#39;尝试解析类型为:

的validatorType
IValidator<Guid>

而不是:

IValidator<Query>

当然找不到任何东西,这意味着我的验证没有运行。

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

1 个答案:

答案 0 :(得分:0)

睡过之后,我自己找到了答案。

我向我的控制器发布了一个Guid,而不是我试图验证的模型(只包含一个guid)

在发布正确的模型后,它现在可以正确验证。