Validating with a Service Layer (VB)
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.vb
[!code-vbMain]
1: Public Class ProductRepository
2: Implements IProductRepository
3:
4: Private _entities As New ProductDBEntities()
5:
6:
7: Public Function ListProducts() As IEnumerable(Of Product) Implements IProductRepository.ListProducts
8: Return _entities.ProductSet.ToList()
9: End Function
10:
11:
12: Public Function CreateProduct(ByVal productToCreate As Product) As Boolean Implements IProductRepository.CreateProduct
13: Try
14: _entities.AddToProductSet(productToCreate)
15: _entities.SaveChanges()
16: Return True
17: Catch
18: Return False
19: End Try
20: End Function
21:
22: End Class
23:
24: Public Interface IProductRepository
25: Function CreateProduct(ByVal productToCreate As Product) As Boolean
26: Function ListProducts() As IEnumerable(Of Product)
27: End Interface
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.vb
[!code-vbMain]
1: Public Class ProductController
2: Inherits Controller
3:
4: Private _repository As IProductRepository
5:
6: Public Sub New()
7: Me.New(New ProductRepository())
8: End Sub
9:
10:
11: Public Sub New(ByVal repository As IProductRepository)
12: _repository = repository
13: End Sub
14:
15:
16: Public Function Index() As ActionResult
17: Return View(_repository.ListProducts())
18: End Function
19:
20:
21: '
22: ' GET: /Product/Create
23:
24: Public Function Create() As ActionResult
25: Return View()
26: End Function
27:
28: '
29: ' POST: /Product/Create
30:
31: <AcceptVerbs(HttpVerbs.Post)> _
32: Public Function Create(<Bind(Exclude:="Id")> ByVal productToCreate As Product) As ActionResult
33: _repository.CreateProduct(productToCreate)
34: Return RedirectToAction("Index")
35: End Function
36:
37: End Class
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.vb
[!code-vbMain]
1: Public Class ProductService
2: Implements IProductService
3:
4: Private _modelState As ModelStateDictionary
5: Private _repository As IProductRepository
6:
7: Public Sub New(ByVal modelState As ModelStateDictionary, ByVal repository As IProductRepository)
8: _modelState = modelState
9: _repository = repository
10: End Sub
11:
12: Protected Function ValidateProduct(ByVal productToValidate As Product) As Boolean
13: If productToValidate.Name.Trim().Length = 0 Then
14: _modelState.AddModelError("Name", "Name is required.")
15: End If
16: If productToValidate.Description.Trim().Length = 0 Then
17: _modelState.AddModelError("Description", "Description is required.")
18: End If
19: If productToValidate.UnitsInStock
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.vb
[!code-vbMain]
1: Public Class ProductController
2: Inherits Controller
3:
4: Private _service As IProductService
5:
6: Public Sub New()
7: _service = New ProductService(Me.ModelState, New ProductRepository())
8: End Sub
9:
10: Public Sub New(ByVal service As IProductService)
11: _service = service
12: End Sub
13:
14:
15: Public Function Index() As ActionResult
16: Return View(_service.ListProducts())
17: End Function
18:
19:
20: '
21: ' GET: /Product/Create
22:
23: Public Function Create() As ActionResult
24: Return View()
25: End Function
26:
27: '
28: ' POST: /Product/Create
29:
30: <AcceptVerbs(HttpVerbs.Post)> _
31: Public Function Create(<Bind(Exclude := "Id")> ByVal productToCreate As Product) As ActionResult
32: If Not _service.CreateProduct(productToCreate) Then
33: Return View()
34: End If
35: Return RedirectToAction("Index")
36: End Function
37:
38: End Class
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.vb (decoupled)
[!code-vbMain]
1: Public Class ProductService
2: Implements IProductService
3:
4: Private _validatonDictionary As IValidationDictionary
5: Private _repository As IProductRepository
6:
7: Public Sub New(ByVal validationDictionary As IValidationDictionary, ByVal repository As IProductRepository)
8: _validatonDictionary = validationDictionary
9: _repository = repository
10: End Sub
11:
12: Protected Function ValidateProduct(ByVal productToValidate As Product) As Boolean
13: If productToValidate.Name.Trim().Length = 0 Then
14: _validatonDictionary.AddError("Name", "Name is required.")
15: End If
16: If productToValidate.Description.Trim().Length = 0 Then
17: _validatonDictionary.AddError("Description", "Description is required.")
18: End If
19: If productToValidate.UnitsInStock
The IValidationDictionary interface is defined in Listing 6. This simple interface has a single method and a single property.
Listing 6 - Models.cs
[!code-vbMain]
1: Public Interface IValidationDictionary
2: Sub AddError(ByVal key As String, ByVal errorMessage As String)
3: ReadOnly Property IsValid() As Boolean
4: End Interface
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.vb
[!code-vbMain]
1: Public Class ModelStateWrapper
2: Implements IValidationDictionary
3:
4: Private _modelState As ModelStateDictionary
5:
6: Public Sub New(ByVal modelState As ModelStateDictionary)
7: _modelState = modelState
8: End Sub
9:
10: #Region "IValidationDictionary Members"
11:
12: Public Sub AddError(ByVal key As String, ByVal errorMessage As String) Implements IValidationDictionary.AddError
13: _modelState.AddModelError(key, errorMessage)
14: End Sub
15:
16: Public ReadOnly Property IsValid() As Boolean Implements IValidationDictionary.IsValid
17: Get
18: Return _modelState.IsValid
19: End Get
20: End Property
21:
22: #End Region
23:
24: End Class
Finally, the updated controller in Listing 8 uses the ModelStateWrapper when creating the service layer in its constructor.
Listing 8 - Controllers.vb
[!code-vbMain]
1: Public Class ProductController
2: Inherits Controller
3:
4: Private _service As IProductService
5:
6: Public Sub New()
7: _service = New ProductService(New ModelStateWrapper(Me.ModelState), New ProductRepository())
8: End Sub
9:
10: Public Sub New(ByVal service As IProductService)
11: _service = service
12: End Sub
13:
14:
15: Public Function Index() As ActionResult
16: Return View(_service.ListProducts())
17: End Function
18:
19:
20: '
21: ' GET: /Product/Create
22:
23: Public Function Create() As ActionResult
24: Return View()
25: End Function
26:
27: '
28: ' POST: /Product/Create
29:
30: <AcceptVerbs(HttpVerbs.Post)> _
31: Public Function Create(<Bind(Exclude := "Id")> ByVal productToCreate As Product) As ActionResult
32: If Not _service.CreateProduct(productToCreate) Then
33: Return View()
34: End If
35: Return RedirectToAction("Index")
36: End Function
37:
38: End Class
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.
|