2012-09-01 26 views
6

Tôi cần có khả năng cung cấp số IComponentContext cho số ValidatorFactory của mình để giải quyết Trình xác nhận hợp lệ FluentValidation. Tôi bị kẹt một chút.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; 
     } 
    } 

Làm thế nào để tạo ra khung cảnh và đăng ký ValidatorFactory

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

Trả lời

0

tôi figured this out. Nếu bạn có ValidatorFactory mất IComponentContext, Autofac sẽ tự động bơm nó.

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

Đăng ký ValidatorFactory

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

Bạn nên cung cấp mã chính xác trong câu trả lời của mình và sau đó đánh dấu nó là câu trả lời. –

+0

@ErikFunkenbusch Mã này chính xác. Tôi đã chấp nhận câu trả lời của tôi. – Sam

9

Thay vì chặt vài nó để Autofac, bạn có thể làm cho nó áp dụng chung cho bất kỳ DependencyResolver bằng cách sử dụng trực tiếp:

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

Sau đó, bạn có thể đăng ký trình xác thực của mình với bất kỳ loại nào của DependencyResolver là kiểu được đánh máy mạnh IValidator<T> và nó sẽ luôn kết thúc giải quyết.

+0

Rất tuyệt! Tôi thích nó ... Tôi đánh dấu của bạn như là câu trả lời thay vì tôi chỉ cho một thực tế là nó là chung chung ngay bây giờ! Cảm ơn – Sam

Các vấn đề liên quan