2012-09-01 12 views
6

Ich muss die IComponentContext zu meiner ValidatorFactory zur Verfügung stellen können, um FluentValidation Validators aufzulösen. Ich bin ein bisschen fest.FluentValidation Autofac ValidatorFactory

ValidatorFactory

public class ValidatorFactory : ValidatorFactoryBase 
    { 
     private readonly IComponentContext context; 

     public ValidatorFactory(IComponentContext context) 
     { 
      this.context = context; 
     } 

     public override IValidator CreateInstance(Type validatorType) 
     { 
      return context.Resolve(validatorType) as IValidator; 
     } 
    } 

Wie stelle ich den Kontext und das ich das herausgefunden ValidatorFactory

FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory()); 

Antwort

0

registrieren. Wenn Sie die ValidatorFactory nehmen IComponentContext, Autofac injiziert es automatisch.

ValidatorFactory

public class ValidatorFactory : ValidatorFactoryBase 
    { 
     private readonly IComponentContext context; 

     public ValidatorFactory(IComponentContext context) 
     { 
      this.context = context; 
     } 

     public override IValidator CreateInstance(Type validatorType) 
     { 
      return context.Resolve(validatorType) as IValidator; 
     } 
    } 

Registrieren Sie den ValidatorFactory

FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory()); 
+3

Sie sollten den richtigen Code in Ihrer Antwort angeben und ihn dann auch als Antwort markieren. –

+0

@ErikFunkenbusch Der Code ist korrekt. Ich habe meine Antwort akzeptiert. – Sam

9

Anstatt fest Paar es Autofac, können Sie es auf jede DependencyResolver allgemein anwendbar machen, indem das direkt mit:

public class ModelValidatorFactory : IValidatorFactory 
{ 
    public IValidator GetValidator(Type type) 
    { 
    if (type == null) 
    { 
     throw new ArgumentNullException("type"); 
    } 
    return DependencyResolver.Current.GetService(typeof(IValidator<>).MakeGenericType(type)) as IValidator; 
    } 

    public IValidator<T> GetValidator<T>() 
    { 
    return DependencyResolver.Current.GetService<IValidator<T>>(); 
    } 
} 

Dann können Sie Ihre Validatoren mit registrieren jede Art von DependencyResolver als stark typisierte IValidator<T> und es wird immer am Ende auflösen.

+0

Schön! Ich mag es ... Ich habe Ihre als die Antwort anstelle von mir markiert nur für die Tatsache, dass es jetzt Generika ist! Vielen Dank – Sam