Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The solution given by that article mixes validation logic with the service logic. These are two concerns and they should be separated. When your application grows you will quickly find out that validation logic gets complicated and gets duplicated throughout the service layer.</p> <p>Therefore, I like to suggest a different approach.</p> <p>First of all, it would be much better IMO to let the service layer throw an exception when a validation error occurred. This would make it much more explicit and much harder to forget to check for errors. This leaves the way the errors are handled to the presentation layer. The <code>ProductController</code> will look like this:</p> <pre><code>public class ProductController : Controller { public ActionResult Create( [Bind(Exclude = "Id")] Product productToCreate) { try { this.service.CreateProduct(productToCreate); } catch (ValidationException ex) { this.ModelState.AddModelErrors(ex); return View(); } return RedirectToAction("Index"); } } public static class MvcValidationExtension { public static void AddModelErrors(this ModelStateDictionary state, ValidationException exception) { foreach (var error in exception.Errors) state.AddModelError(error.Key, error.Message); } } </code></pre> <p>The <code>ProductService</code> class should not itself have any validation in it, but should delegate that to a class specialized to validation: the <code>IValidationProvider</code>:</p> <pre><code>public interface IValidationProvider { void Validate(object entity); void ValidateAll(IEnumerable entities); } public class ProductService : IProductService { private readonly IValidationProvider validationProvider; private readonly IProductRespository repository; public ProductService(IProductRespository repository, IValidationProvider validationProvider) { this.repository = repository; this.validationProvider = validationProvider; } // Does not return an error code anymore. Just throws an exception public void CreateProduct(Product productToCreate) { // Do validation here or perhaps even in the repository... this.validationProvider.Validate(productToCreate); // This call should also throw on failure. this.repository.CreateProduct(productToCreate); } } </code></pre> <p>The <code>IValidationProvider</code> should not validate itself, but delegate the validation to validation classes that are specialized in validation one specific type. When an object (or set of objects) is not valid, the validation provider should throw a <code>ValidationException</code>, that can be caught higher up the call stack. The implementation of the provider could look like this:</p> <pre><code>sealed class ValidationProvider : IValidationProvider { private readonly Func&lt;Type, IValidator&gt; validatorFactory; public ValidationProvider(Func&lt;Type, IValidator&gt; validatorFactory) { this.validatorFactory = validatorFactory; } public void Validate(object entity) { var results = this.validatorFactory(entity.GetType()) .Validate(entity).ToArray(); if (results.Length &gt; 0) throw new ValidationException(results); } public void ValidateAll(IEnumerable entities) { var results = ( from entity in entities.Cast&lt;object&gt;() let validator = this.validatorFactory(entity.GetType()) from result in validator.Validate(entity) select result).ToArray(); if (results.Length &gt; 0) throw new ValidationException(results); } } </code></pre> <p>The <code>ValidationProvider</code> depends on <code>IValidator</code> instances, that do the actual validation. The provider itself doesn't know how to create those instances, but uses the injected <code>Func&lt;Type, IValidator&gt;</code> delegate for that. This method will have container specific code, for instance this for Ninject:</p> <pre><code>var provider = new ValidationProvider(type =&gt; { var valType = typeof(Validator&lt;&gt;).MakeGenericType(type); return (IValidator)kernel.Get(valType); }); </code></pre> <p>This snippet shows a <code>Validator&lt;T&gt;</code> class. I will show this in a second. First, the <code>ValidationProvider</code> depends on the following classes:</p> <pre><code>public interface IValidator { IEnumerable&lt;ValidationResult&gt; Validate(object entity); } public class ValidationResult { public ValidationResult(string key, string message) { this.Key = key; this.Message = message; } public string Key { get; private set; } public string Message { get; private set; } } public class ValidationException : Exception { public ValidationException(IEnumerable&lt;ValidationResult&gt; r) : base(GetFirstErrorMessage(r)) { this.Errors = new ReadOnlyCollection&lt;ValidationResult&gt;(r.ToArray()); } public ReadOnlyCollection&lt;ValidationResult&gt; Errors { get; private set; } private static string GetFirstErrorMessage( IEnumerable&lt;ValidationResult&gt; errors) { return errors.First().Message; } } </code></pre> <p>All the above code is the plumbing needed to get the validation in place. We can now define a validation class per entity we want to validate. However, to help our IoC container out a bit, we should define a generic base class for the validators. This will allow us to register the validation types:</p> <pre><code>public abstract class Validator&lt;T&gt; : IValidator { IEnumerable&lt;ValidationResult&gt; IValidator.Validate(object entity) { if (entity == null) throw new ArgumentNullException("entity"); return this.Validate((T)entity); } protected abstract IEnumerable&lt;ValidationResult&gt; Validate(T entity); } </code></pre> <p>As you can see, this abstract class inherits from <code>IValidator</code>. Now we can define a <code>ProductValidator</code> class that derives from <code>Validator&lt;Product&gt;</code>:</p> <pre><code>public sealed class ProductValidator : Validator&lt;Product&gt; { protected override IEnumerable&lt;ValidationResult&gt; Validate( Product entity) { if (entity.Name.Trim().Length == 0) yield return new ValidationResult("Name", "Name is required."); if (entity.Description.Trim().Length == 0) yield return new ValidationResult("Description", "Description is required."); if (entity.UnitsInStock &lt; 0) yield return new ValidationResult("UnitsInStock", "Units in stock cnnot be less than zero."); } } </code></pre> <p>As you can see the <code>ProductValidator</code> class uses the C# <code>yield return</code> statement which makes returning validation errors more easy.</p> <p>The last thing we should do to get this all working, is setting up the Ninject configuration:</p> <pre><code>kernel.Bind&lt;IProductService&gt;().To&lt;ProductService&gt;(); kernel.Bind&lt;IProductRepository&gt;().To&lt;L2SProductRepository&gt;(); Func&lt;Type, IValidator&gt; validatorFactory = type =&gt; { var valType = typeof(Validator&lt;&gt;).MakeGenericType(type); return (IValidator)kernel.Get(valType); }; kernel.Bind&lt;IValidationProvider&gt;() .ToConstant(new ValidationProvider(validatorFactory)); kernel.Bind&lt;Validator&lt;Product&gt;&gt;().To&lt;ProductValidator&gt;(); </code></pre> <p>Are we really done? It depends. Downside of the configuration above is that for each entity in our domain we will need a <code>Validator&lt;T&gt;</code> implementation. Even when perhaps most implementations will be empty.</p> <p>We can solve this problem by doing two things: 1. We can use batch registration to automatically load all implementations dynamically from a given assembly. 2. We can revert to a default implementation when no registration exists.</p> <p>Such a default implementation could look like this:</p> <pre><code>sealed class NullValidator&lt;T&gt; : Validator&lt;T&gt; { protected override IEnumerable&lt;ValidationResult&gt; Validate(T entity) { return Enumerable.Empty&lt;ValidationResult&gt;(); } } </code></pre> <p>We can configure this <code>NullValidator&lt;T&gt;</code> as follows:</p> <pre><code>kernel.Bind(typeof(Validator&lt;&gt;)).To(typeof(NullValidator&lt;&gt;)); </code></pre> <p>After doing this, Ninject will return a <code>NullValidator&lt;Customer&gt;</code> when a <code>Validator&lt;Customer&gt;</code> is requested and no specific implementation is registered for it.</p> <p>The last thing that's missing now is automatic registration (or batch registration). This will save you from having to add a registration per <code>Validator&lt;T&gt;</code> implementation and let Ninject search your assemblies dynamically for you. I couldn't find any examples of this, but I assume Ninject can do this.</p> <p><strong>UPDATE:</strong> See <a href="https://stackoverflow.com/a/40284170/264697">Kayess' answer</a> to learn how to batch register these types.</p> <p>One last note: To get this done you need quite a lot of plumbing, so if your project is (and stays) fairly little, this approach might give you too much overhead. When your project grows however, you will be very glad when you have such a flexible design. Think about what you have to do if you want to change the validation to say Validation Application Block or DataAnnotations. The only thing you have to do is to write an implementation for the <code>NullValidator&lt;T&gt;</code> (I would rename it to <code>DefaultValidator&lt;T&gt;</code> in that case. Besides that, it is still possible to have your custom validation classes for extra validations that are hard with VAB or DataAnnotations.</p> <p><strong>Note that the use of abstractions such as <code>IProductService</code> and <code>ICustomerService</code> violates the SOLID principles and you might benefit from moving from this pattern to <a href="https://cuttingedge.it/blogs/steven/pivot/entry.php?id=91" rel="nofollow noreferrer">a pattern that abstracts use cases</a>.</strong></p> <p>Update: Also take a look at <a href="https://stackoverflow.com/q/16793982/264697">this q/a</a>; it discusses a follow-up question about the same article.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload