Validating with a Service Layer (C#)
Learn how to move your validation logic out of your controller actions and into a separate service layer. In this tutorial, Stephen Walther explains how you can maintain a sharp separation of concerns by isolating your service layer from your controller layer.
The goal of this tutorial is to describe one method of performing validation in an ASP.NET MVC application. In this tutorial, you learn how to move your validation logic out of your controllers and into a separate service layer.
Separating Concerns
When you build an ASP.NET MVC application, you should not place your database logic inside your controller actions. Mixing your database and controller logic makes your application more difficult to maintain over time. The recommendation is that you place all of your database logic in a separate repository layer.
For example, Listing 1 contains a simple repository named the ProductRepository. The product repository contains all of the data access code for the application. The listing also includes the IProductRepository interface that the product repository implements.
Listing 1 – Models.cs
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.Linq;
3:
4: namespace MvcApplication1.Models
5: {
6: public class ProductRepository : MvcApplication1.Models.IProductRepository
7: {
8: private ProductDBEntities _entities = new ProductDBEntities();
9:
10: public IEnumerable<Product> ListProducts()
11: {
12: return _entities.ProductSet.ToList();
13: }
14:
15: public bool CreateProduct(Product productToCreate)
16: {
17: try
18: {
19: _entities.AddToProductSet(productToCreate);
20: _entities.SaveChanges();
21: return true;
22: }
23: catch
24: {
25: return false;
26: }
27: }
28:
29: }
30:
31: public interface IProductRepository
32: {
33: bool CreateProduct(Product productToCreate);
34: IEnumerable<Product> ListProducts();
35: }
36:
37: }
The controller in Listing 2 uses the repository layer in both its Index() and Create() actions. Notice that this controller does not contain any database logic. Creating a repository layer enables you to maintain a clean separation of concerns. Controllers are responsible for application flow control logic and the repository is responsible for data access logic.
Listing 2 - Controllers.cs
[!code-csharpMain]
1: using System.Web.Mvc;
2: using MvcApplication1.Models;
3:
4: namespace MvcApplication1.Controllers
5: {
6: public class ProductController : Controller
7: {
8: private IProductRepository _repository;
9:
10: public ProductController():
11: this(new ProductRepository()) {}
12:
13: public ProductController(IProductRepository repository)
14: {
15: _repository = repository;
16: }
17:
18: public ActionResult Index()
19: {
20: return View(_repository.ListProducts());
21: }
22:
23: //
24: // GET: /Product/Create
25:
26: public ActionResult Create()
27: {
28: return View();
29: }
30:
31: //
32: // POST: /Product/Create
33:
34: [AcceptVerbs(HttpVerbs.Post)]
35: public ActionResult Create([Bind(Exclude="Id")] Product productToCreate)
36: {
37: _repository.CreateProduct(productToCreate);
38: return RedirectToAction("Index");
39: }
40:
41: }
42: }
Creating a Service Layer
So, application flow control logic belongs in a controller and data access logic belongs in a repository. In that case, where do you put your validation logic? One option is to place your validation logic in a service layer.
A service layer is an additional layer in an ASP.NET MVC application that mediates communication between a controller and repository layer. The service layer contains business logic. In particular, it contains validation logic.
For example, the product service layer in Listing 3 has a CreateProduct() method. The CreateProduct() method calls the ValidateProduct() method to validate a new product before passing the product to the product repository.
Listing 3 - Models.cs
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.Web.Mvc;
3:
4: namespace MvcApplication1.Models
5: {
6: public class ProductService : MvcApplication1.Models.IProductService
7: {
8:
9: private ModelStateDictionary _modelState;
10: private IProductRepository _repository;
11:
12: public ProductService(ModelStateDictionary modelState, IProductRepository repository)
13: {
14: _modelState = modelState;
15: _repository = repository;
16: }
17:
18: protected bool ValidateProduct(Product productToValidate)
19: {
20: if (productToValidate.Name.Trim().Length == 0)
21: _modelState.AddModelError("Name", "Name is required.");
22: if (productToValidate.Description.Trim().Length == 0)
23: _modelState.AddModelError("Description", "Description is required.");
24: if (productToValidate.UnitsInStock < 0)
25: _modelState.AddModelError("UnitsInStock", "Units in stock cannot be less than zero.");
26: return _modelState.IsValid;
27: }
28:
29: public IEnumerable<Product> ListProducts()
30: {
31: return _repository.ListProducts();
32: }
33:
34: public bool CreateProduct(Product productToCreate)
35: {
36: // Validation logic
37: if (!ValidateProduct(productToCreate))
38: return false;
39:
40: // Database logic
41: try
42: {
43: _repository.CreateProduct(productToCreate);
44: }
45: catch
46: {
47: return false;
48: }
49: return true;
50: }
51:
52: }
53:
54: public interface IProductService
55: {
56: bool CreateProduct(Product productToCreate);
57: IEnumerable<Product> ListProducts();
58: }
59: }
The Product controller has been updated in Listing 4 to use the service layer instead of the repository layer. The controller layer talks to the service layer. The service layer talks to the repository layer. Each layer has a separate responsibility.
Listing 4 - Controllers.cs
[!code-csharpMain]
1: Listing 4 – Controllers\ProductController.cs
2: using System.Web.Mvc;
3: using MvcApplication1.Models;
4:
5: namespace MvcApplication1.Controllers
6: {
7: public class ProductController : Controller
8: {
9: private IProductService _service;
10:
11: public ProductController()
12: {
13: _service = new ProductService(this.ModelState, new ProductRepository());
14: }
15:
16: public ProductController(IProductService service)
17: {
18: _service = service;
19: }
20:
21: public ActionResult Index()
22: {
23: return View(_service.ListProducts());
24: }
25:
26: //
27: // GET: /Product/Create
28:
29: public ActionResult Create()
30: {
31: return View();
32: }
33:
34: //
35: // POST: /Product/Create
36:
37: [AcceptVerbs(HttpVerbs.Post)]
38: public ActionResult Create([Bind(Exclude = "Id")] Product productToCreate)
39: {
40: if (!_service.CreateProduct(productToCreate))
41: return View();
42: return RedirectToAction("Index");
43: }
44:
45: }
46: }
Notice that the product service is created in the product controller constructor. When the product service is created, the model state dictionary is passed to the service. The product service uses model state to pass validation error messages back to the controller.
Decoupling the Service Layer
We have failed to isolate the controller and service layers in one respect. The controller and service layers communicate through model state. In other words, the service layer has a dependency on a particular feature of the ASP.NET MVC framework.
We want to isolate the service layer from our controller layer as much as possible. In theory, we should be able to use the service layer with any type of application and not only an ASP.NET MVC application. For example, in the future, we might want to build a WPF front-end for our application. We should find a way to remove the dependency on ASP.NET MVC model state from our service layer.
In Listing 5, the service layer has been updated so that it no longer uses model state. Instead, it uses any class that implements the IValidationDictionary interface.
Listing 5 - Models.cs (decoupled)
[!code-csharpMain]
1: using System.Collections.Generic;
2:
3: namespace MvcApplication1.Models
4: {
5: public class ProductService : IProductService
6: {
7:
8: private IValidationDictionary _validatonDictionary;
9: private IProductRepository _repository;
10:
11: public ProductService(IValidationDictionary validationDictionary, IProductRepository repository)
12: {
13: _validatonDictionary = validationDictionary;
14: _repository = repository;
15: }
16:
17: protected bool ValidateProduct(Product productToValidate)
18: {
19: if (productToValidate.Name.Trim().Length == 0)
20: _validatonDictionary.AddError("Name", "Name is required.");
21: if (productToValidate.Description.Trim().Length == 0)
22: _validatonDictionary.AddError("Description", "Description is required.");
23: if (productToValidate.UnitsInStock < 0)
24: _validatonDictionary.AddError("UnitsInStock", "Units in stock cannot be less than zero.");
25: return _validatonDictionary.IsValid;
26: }
27:
28: public IEnumerable<Product> ListProducts()
29: {
30: return _repository.ListProducts();
31: }
32:
33: public bool CreateProduct(Product productToCreate)
34: {
35: // Validation logic
36: if (!ValidateProduct(productToCreate))
37: return false;
38:
39: // Database logic
40: try
41: {
42: _repository.CreateProduct(productToCreate);
43: }
44: catch
45: {
46: return false;
47: }
48: return true;
49: }
50:
51: }
52:
53: public interface IProductService
54: {
55: bool CreateProduct(Product productToCreate);
56: System.Collections.Generic.IEnumerable<Product> ListProducts();
57: }
58: }
The IValidationDictionary interface is defined in Listing 6. This simple interface has a single method and a single property.
Listing 6 - Models.cs
[!code-csharpMain]
1: namespace MvcApplication1.Models
2: {
3: public interface IValidationDictionary
4: {
5: void AddError(string key, string errorMessage);
6: bool IsValid { get; }
7: }
8: }
The class in Listing 7, named the ModelStateWrapper class, implements the IValidationDictionary interface. You can instantiate the ModelStateWrapper class by passing a model state dictionary to the constructor.
Listing 7 - Models.cs
[!code-csharpMain]
1: using System.Web.Mvc;
2:
3: namespace MvcApplication1.Models
4: {
5: public class ModelStateWrapper : IValidationDictionary
6: {
7:
8: private ModelStateDictionary _modelState;
9:
10: public ModelStateWrapper(ModelStateDictionary modelState)
11: {
12: _modelState = modelState;
13: }
14:
15: #region IValidationDictionary Members
16:
17: public void AddError(string key, string errorMessage)
18: {
19: _modelState.AddModelError(key, errorMessage);
20: }
21:
22: public bool IsValid
23: {
24: get { return _modelState.IsValid; }
25: }
26:
27: #endregion
28: }
29: }
Finally, the updated controller in Listing 8 uses the ModelStateWrapper when creating the service layer in its constructor.
Listing 8 - Controllers.cs
[!code-csharpMain]
1: using System.Web.Mvc;
2: using MvcApplication1.Models;
3:
4: namespace MvcApplication1.Controllers
5: {
6: public class ProductController : Controller
7: {
8: private IProductService _service;
9:
10: public ProductController()
11: {
12: _service = new ProductService(new ModelStateWrapper(this.ModelState), new ProductRepository());
13: }
14:
15: public ProductController(IProductService service)
16: {
17: _service = service;
18: }
19:
20: public ActionResult Index()
21: {
22: return View(_service.ListProducts());
23: }
24:
25: //
26: // GET: /Product/Create
27:
28: public ActionResult Create()
29: {
30: return View();
31: }
32:
33: //
34: // POST: /Product/Create
35:
36: [AcceptVerbs(HttpVerbs.Post)]
37: public ActionResult Create([Bind(Exclude = "Id")] Product productToCreate)
38: {
39: if (!_service.CreateProduct(productToCreate))
40: return View();
41: return RedirectToAction("Index");
42: }
43:
44: }
45: }
Using the IValidationDictionary interface and the ModelStateWrapper class enables us to completely isolate our service layer from our controller layer. The service layer is no longer dependent on model state. You can pass any class that implements the IValidationDictionary interface to the service layer. For example, a WPF application might implement the IValidationDictionary interface with a simple collection class.
Summary
The goal of this tutorial was to discuss one approach to performing validation in an ASP.NET MVC application. In this tutorial, you learned how to move all of your validation logic out of your controllers and into a separate service layer. You also learned how to isolate your service layer from your controller layer by creating a ModelStateWrapper class.
|