2012-08-31 93 views
1

我一直在ASP.NET MVC 3的View Models中使用FluentValidation,它效果超讚!FluentValidation在服務層?

我想現在使用它作爲我的驗證引擎對我的業務層在我的域對象。

你可以用它做複雜的驗證方案嗎?

我期待這樣的事情:

public class MyService : IMyService 
{ 
    private readonly ISomeOtherService someOtherService; 
    public MyService(ISomeOtherService someOtherService) 
    { 
     this.someOtherService = someOtherService; 
    } 

    public bool SaveObject() 
    { 
     var validator = new MyValidator(someOtherService); 
     if (!validator.IsValid()) 
     { 
      //spin through the validation results, add them to IValidationDictionary which is a ModelState wrapper 

      return false; 
     } 
    } 
} 

public class MyValidator : AbstractValidator<MyObject> 
{ 
    private readonly IOtherService service; 
    public MyValidator(ISomeOtherService service) 
    { 
     // Here I want to be able to perform complex validation rules that may involve other services?? 
    } 
} 

這樣的事情。我也打算使用另一個驗證庫/方案?

謝謝!

回答

1

我通過創建一個ValidationServiceValidatorFactory結合解決了這個問題,我認爲這是一個非常漂亮的解決方案。

這是ValidatorFactory上的線程:FluentValidation Autofac ValidatorFactory