Iteration #4 – Make the application loosely coupled (C#)
by Microsoft
In this third iteration, we take advantage of several software design patterns to make it easier to maintain and modify the Contact Manager application. For example, we refactor our application to use the Repository pattern and the Dependency Injection pattern.
Building a Contact Management ASP.NET MVC Application (C#)
In this series of tutorials, we build an entire Contact Management application from start to finish. The Contact Manager application enables you to store contact information - names, phone numbers and email addresses - for a list of people.
We build the application over multiple iterations. With each iteration, we gradually improve the application. The goal of this multiple iteration approach is to enable you to understand the reason for each change.
Iteration #1 - Create the application. In the first iteration, we create the Contact Manager in the simplest way possible. We add support for basic database operations: Create, Read, Update, and Delete (CRUD).
Iteration #2 - Make the application look nice. In this iteration, we improve the appearance of the application by modifying the default ASP.NET MVC view master page and cascading style sheet.
Iteration #3 - Add form validation. In the third iteration, we add basic form validation. We prevent people from submitting a form without completing required form fields. We also validate email addresses and phone numbers.
Iteration #4 - Make the application loosely coupled. In this third iteration, we take advantage of several software design patterns to make it easier to maintain and modify the Contact Manager application. For example, we refactor our application to use the Repository pattern and the Dependency Injection pattern.
Iteration #5 - Create unit tests. In the fifth iteration, we make our application easier to maintain and modify by adding unit tests. We mock our data model classes and build unit tests for our controllers and validation logic.
Iteration #6 - Use test-driven development. In this sixth iteration, we add new functionality to our application by writing unit tests first and writing code against the unit tests. In this iteration, we add contact groups.
Iteration #7 - Add Ajax functionality. In the seventh iteration, we improve the responsiveness and performance of our application by adding support for Ajax.
This Iteration
In this fourth iteration of the Contact Manager application, we refactor the application to make the application more loosely coupled. When an application is loosely coupled, you can modify the code in one part of the application without needing to modify the code in other parts of the application. Loosely coupled applications are more resilient to change.
Currently, all of the data access and validation logic used by the Contact Manager application is contained in the controller classes. This is a bad idea. Whenever you need to modify one part of your application, you risk introducing bugs into another part of your application. For example, if you modify your validation logic, you risk introducing new bugs into your data access or controller logic.
[!NOTE]
(SRP), a class should never have more than one reason to change. Mixing controller, validation, and database logic is a massive violation of the Single Responsibility Principle.
There are several reasons that you might need to modify your application. You might need to add a new feature to your application, you might need to fix a bug in your application, or you might need to modify how a feature of your application is implemented. Applications are rarely static. They tend to grow and mutate over time.
Imagine, for example, that you decide to change how you implement your data access layer. Right now, the Contact Manager application uses the Microsoft Entity Framework to access the database. However, you might decide to migrate to a new or alternative data access technology such as ADO.NET Data Services or NHibernate. However, because the data access code is not isolated from the validation and controller code, there is no way to modify the data access code in your application without modifying other code that is not directly related to data access.
When an application is loosely coupled, on the other hand, you can make changes to one part of an application without touching other parts of an application. For example, you can switch data access technologies without modifying your validation or controller logic.
In this iteration, we take advantage of several software design patterns that enable us to refactor our Contact Manager application into a more loosely coupled application. When we are done, the Contact Manager won t do anything that it didn t do before. However, we’ll be able to change the application more easily in the future.
[!NOTE]
Refactoring is the process of rewriting an application in such a way that it does not lose any existing functionality.
Using the Repository Software Design Pattern
Our first change is to take advantage of a software design pattern called the Repository pattern. We’ll use the Repository pattern to isolate our data access code from the rest of our application.
Implementing the Repository pattern requires us to complete the following two steps:
- Create an interface
- Create a concrete class that implements the interface
First, we need to create an interface that describes all of the data access methods that we need to perform. The IContactManagerRepository interface is contained in Listing 1. This interface describes five methods: CreateContact(), DeleteContact(), EditContact(), GetContact, and ListContacts().
Listing 1 - Models.cs
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3:
4: namespace ContactManager.Models
5: {
6: public interface IContactRepository
7: {
8: Contact CreateContact(Contact contactToCreate);
9: void DeleteContact(Contact contactToDelete);
10: Contact EditContact(Contact contactToUpdate);
11: Contact GetContact(int id);
12: IEnumerable<Contact> ListContacts();
13:
14: }
15: }
Next, we need to create a concrete class that implements the IContactManagerRepository interface. Because we are using the Microsoft Entity Framework to access the database, we’ll create a new class named EntityContactManagerRepository. This class is contained in Listing 2.
Listing 2 - Models.cs
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.Linq;
3:
4: namespace ContactManager.Models
5: {
6: public class EntityContactManagerRepository : ContactManager.Models.IContactManagerRepository
7: {
8: private ContactManagerDBEntities _entities = new ContactManagerDBEntities();
9:
10: public Contact GetContact(int id)
11: {
12: return (from c in _entities.ContactSet
13: where c.Id == id
14: select c).FirstOrDefault();
15: }
16:
17: public IEnumerable ListContacts()
18: {
19: return _entities.ContactSet.ToList();
20: }
21:
22: public Contact CreateContact(Contact contactToCreate)
23: {
24: _entities.AddToContactSet(contactToCreate);
25: _entities.SaveChanges();
26: return contactToCreate;
27: }
28:
29: public Contact EditContact(Contact contactToEdit)
30: {
31: var originalContact = GetContact(contactToEdit.Id);
32: _entities.ApplyPropertyChanges(originalContact.EntityKey.EntitySetName, contactToEdit);
33: _entities.SaveChanges();
34: return contactToEdit;
35: }
36:
37: public void DeleteContact(Contact contactToDelete)
38: {
39: var originalContact = GetContact(contactToDelete.Id);
40: _entities.DeleteObject(originalContact);
41: _entities.SaveChanges();
42: }
43:
44: }
45: }
Notice that the EntityContactManagerRepository class implements the IContactManagerRepository interface. The class implements all five of the methods described by that interface.
You might wonder why we need to bother with an interface. Why do we need to create both an interface and a class that implements it?
With one exception, the remainder of our application will interact with the interface and not the concrete class. Instead of calling the methods exposed by the EntityContactManagerRepository class, we’ll call the methods exposed by the IContactManagerRepository interface.
That way, we can implement the interface with a new class without needing to modify the remainder of our application. For example, at some future date, we might want to implement an DataServicesContactManagerRepository class that implements the IContactManagerRepository interface. The DataServicesContactManagerRepository class might use ADO.NET Data Services to access a database instead of the Microsoft Entity Framework.
If our application code is programmed against the IContactManagerRepository interface instead of the concrete EntityContactManagerRepository class then we can switch concrete classes without modifying any of the rest of our code. For example, we can switch from the EntityContactManagerRepository class to the DataServicesContactManagerRepository class without modifying our data access or validation logic.
Programming against interfaces (abstractions) instead of concrete classes makes our application more resilient to change.
[!NOTE]
You can quickly create an interface from a concrete class within Visual Studio by selecting the menu option Refactor, Extract Interface. For example, you can create the EntityContactManagerRepository class first and then use Extract Interface to generate the IContactManagerRepository interface automatically.
Using the Dependency Injection Software Design Pattern
Now that we have migrated our data access code to a separate Repository class, we need to modify our Contact controller to use this class. We will take advantage of a software design pattern called Dependency Injection to use the Repository class in our controller.
The modified Contact controller is contained in Listing 3.
Listing 3 - Controllers.cs
[!code-csharpMain]
1: using System.Text.RegularExpressions;
2: using System.Web.Mvc;
3: using ContactManager.Models;
4:
5: namespace ContactManager.Controllers
6: {
7: public class ContactController : Controller
8: {
9: private IContactManagerRepository _repository;
10:
11: public ContactController()
12: : this(new EntityContactManagerRepository())
13: {}
14:
15: public ContactController(IContactManagerRepository repository)
16: {
17: _repository = repository;
18: }
19:
20: protected void ValidateContact(Contact contactToValidate)
21: {
22: if (contactToValidate.FirstName.Trim().Length == 0)
23: ModelState.AddModelError("FirstName", "First name is required.");
24: if (contactToValidate.LastName.Trim().Length == 0)
25: ModelState.AddModelError("LastName", "Last name is required.");
26: if (contactToValidate.Phone.Length > 0 && !Regex.IsMatch(contactToValidate.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
27: ModelState.AddModelError("Phone", "Invalid phone number.");
28: if (contactToValidate.Email.Length > 0 && !Regex.IsMatch(contactToValidate.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
29: ModelState.AddModelError("Email", "Invalid email address.");
30: }
31:
32: public ActionResult Index()
33: {
34: return View(_repository.ListContacts());
35: }
36:
37: public ActionResult Create()
38: {
39: return View();
40: }
41:
42: [AcceptVerbs(HttpVerbs.Post)]
43: public ActionResult Create([Bind(Exclude = "Id")] Contact contactToCreate)
44: {
45: // Validation logic
46: ValidateContact(contactToCreate);
47: if (!ModelState.IsValid)
48: return View();
49:
50: // Database logic
51: try
52: {
53: _repository.CreateContact(contactToCreate);
54: return RedirectToAction("Index");
55: }
56: catch
57: {
58: return View();
59: }
60: }
61:
62: public ActionResult Edit(int id)
63: {
64: return View(_repository.GetContact(id));
65: }
66:
67: [AcceptVerbs(HttpVerbs.Post)]
68: public ActionResult Edit(Contact contactToEdit)
69: {
70: // Validation logic
71: ValidateContact(contactToEdit);
72: if (!ModelState.IsValid)
73: return View();
74:
75: // Database logic
76: try
77: {
78: _repository.EditContact(contactToEdit);
79: return RedirectToAction("Index");
80: }
81: catch
82: {
83: return View();
84: }
85: }
86:
87: public ActionResult Delete(int id)
88: {
89: return View(_repository.GetContact(id));
90: }
91:
92: [AcceptVerbs(HttpVerbs.Post)]
93: public ActionResult Delete(Contact contactToDelete)
94: {
95: try
96: {
97: _repository.DeleteContact(contactToDelete);
98: return RedirectToAction("Index");
99: }
100: catch
101: {
102: return View();
103: }
104: }
105:
106: }
107: }
Notice that the Contact controller in Listing 3 has two constructors. The first constructor passes a concrete instance of the IContactManagerRepository interface to the second constructor. The Contact controller class uses Constructor Dependency Injection.
The one and only place that the EntityContactManagerRepository class is used is in the first constructor. The remainder of the class uses the IContactManagerRepository interface instead of the concrete EntityContactManagerRepository class.
This makes it easy to switch implementations of the IContactManagerRepository class in the future. If you want to use the DataServicesContactRepository class instead of the EntityContactManagerRepository class, just modify the first constructor.
Constructor Dependency injection also makes the Contact controller class very testable. In your unit tests, you can instantiate the Contact controller by passing a mock implementation of the IContactManagerRepository class. This feature of Dependency Injection will be very important to us in the next iteration when we build unit tests for the Contact Manager application.
[!NOTE]
If you want to completely decouple the Contact controller class from a particular implementation of the IContactManagerRepository interface then you can take advantage of a framework that supports Dependency Injection such as StructureMap or the Microsoft Entity Framework (MEF). By taking advantage of a Dependency Injection framework, you never need to refer to a concrete class in your code.
Creating a Service Layer
You might have noticed that our validation logic is still mixed up with our controller logic in the modified controller class in Listing 3. For the same reason that it is a good idea to isolate our data access logic, it is a good idea to isolate our validation logic.
To fix this problem, we can create a separate service layer. The service layer is a separate layer that we can insert between our controller and repository classes. The service layer contains our business logic including all of our validation logic.
The ContactManagerService is contained in Listing 4. It contains the validation logic from the Contact controller class.
Listing 4 - Models.cs
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.Text.RegularExpressions;
3: using System.Web.Mvc;
4: using ContactManager.Models.Validation;
5:
6: namespace ContactManager.Models
7: {
8: public class ContactManagerService : IContactManagerService
9: {
10: private IValidationDictionary _validationDictionary;
11: private IContactManagerRepository _repository;
12:
13: public ContactManagerService(IValidationDictionary validationDictionary)
14: : this(validationDictionary, new EntityContactManagerRepository())
15: {}
16:
17: public ContactManagerService(IValidationDictionary validationDictionary, IContactManagerRepository repository)
18: {
19: _validationDictionary = validationDictionary;
20: _repository = repository;
21: }
22:
23: public bool ValidateContact(Contact contactToValidate)
24: {
25: if (contactToValidate.FirstName.Trim().Length == 0)
26: _validationDictionary.AddError("FirstName", "First name is required.");
27: if (contactToValidate.LastName.Trim().Length == 0)
28: _validationDictionary.AddError("LastName", "Last name is required.");
29: if (contactToValidate.Phone.Length > 0 && !Regex.IsMatch(contactToValidate.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
30: _validationDictionary.AddError("Phone", "Invalid phone number.");
31: if (contactToValidate.Email.Length > 0 && !Regex.IsMatch(contactToValidate.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
32: _validationDictionary.AddError("Email", "Invalid email address.");
33: return _validationDictionary.IsValid;
34: }
35:
36: #region IContactManagerService Members
37:
38: public bool CreateContact(Contact contactToCreate)
39: {
40: // Validation logic
41: if (!ValidateContact(contactToCreate))
42: return false;
43:
44: // Database logic
45: try
46: {
47: _repository.CreateContact(contactToCreate);
48: }
49: catch
50: {
51: return false;
52: }
53: return true;
54: }
55:
56: public bool EditContact(Contact contactToEdit)
57: {
58: // Validation logic
59: if (!ValidateContact(contactToEdit))
60: return false;
61:
62: // Database logic
63: try
64: {
65: _repository.EditContact(contactToEdit);
66: }
67: catch
68: {
69: return false;
70: }
71: return true;
72: }
73:
74: public bool DeleteContact(Contact contactToDelete)
75: {
76: try
77: {
78: _repository.DeleteContact(contactToDelete);
79: }
80: catch
81: {
82: return false;
83: }
84: return true;
85: }
86:
87: public Contact GetContact(int id)
88: {
89: return _repository.GetContact(id);
90: }
91:
92: public IEnumerable<Contact> ListContacts()
93: {
94: return _repository.ListContacts();
95: }
96:
97: #endregion
98: }
99: }
Notice that the constructor for the ContactManagerService requires a ValidationDictionary. The service layer communicates with the controller layer through this ValidationDictionary. We discuss the ValidationDictionary in detail in the following section when we discuss the Decorator pattern.
Notice, furthermore, that the ContactManagerService implements the IContactManagerService interface. You should always strive to program against interfaces instead of concrete classes. Other classes in the Contact Manager application do not interact with the ContactManagerService class directly. Instead, with one exception, the remainder of the Contact Manager application is programmed against the IContactManagerService interface.
The IContactManagerService interface is contained in Listing 5.
Listing 5 - Models.cs
[!code-csharpMain]
1: using System.Collections.Generic;
2:
3: namespace ContactManager.Models
4: {
5: public interface IContactManagerService
6: {
7: bool CreateContact(Contact contactToCreate);
8: bool DeleteContact(Contact contactToDelete);
9: bool EditContact(Contact contactToEdit);
10: Contact GetContact(int id);
11: IEnumerable ListContacts();
12: }
13: }
The modified Contact controller class is contained in Listing 6. Notice that the Contact controller no longer interacts with the ContactManager repository. Instead, the Contact controller interacts with the ContactManager service. Each layer is isolated as much as possible from other layers.
Listing 6 - Controllers.cs
[!code-csharpMain]
1: using System.Web.Mvc;
2: using ContactManager.Models;
3:
4: namespace ContactManager.Controllers
5: {
6: public class ContactController : Controller
7: {
8: private IContactManagerService _service;
9:
10: public ContactController()
11: {
12: _service = new ContactManagerService(new ModelStateWrapper(this.ModelState));
13:
14: }
15:
16: public ContactController(IContactManagerService service)
17: {
18: _service = service;
19: }
20:
21: public ActionResult Index()
22: {
23: return View(_service.ListContacts());
24: }
25:
26: public ActionResult Create()
27: {
28: return View();
29: }
30:
31: [AcceptVerbs(HttpVerbs.Post)]
32: public ActionResult Create([Bind(Exclude = "Id")] Contact contactToCreate)
33: {
34: if (_service.CreateContact(contactToCreate))
35: return RedirectToAction("Index");
36: return View();
37: }
38:
39: public ActionResult Edit(int id)
40: {
41: return View(_service.GetContact(id));
42: }
43:
44: [AcceptVerbs(HttpVerbs.Post)]
45: public ActionResult Edit(Contact contactToEdit)
46: {
47: if (_service.EditContact(contactToEdit))
48: return RedirectToAction("Index");
49: return View();
50: }
51:
52: public ActionResult Delete(int id)
53: {
54: return View(_service.GetContact(id));
55: }
56:
57: [AcceptVerbs(HttpVerbs.Post)]
58: public ActionResult Delete(Contact contactToDelete)
59: {
60: if (_service.DeleteContact(contactToDelete))
61: return RedirectToAction("Index");
62: return View();
63: }
64:
65: }
66: }
Our application no longer runs afoul of the Single Responsibility Principle (SRP). The Contact controller in Listing 6 has been stripped of every responsibility other than controlling the flow of application execution. All the validation logic has been removed from the Contact controller and pushed into the service layer. All of the database logic has been pushed into the repository layer.
Using the Decorator Pattern
We want to be able to completely decouple our service layer from our controller layer. In principle, we should be able to compile our service layer in a separate assembly from our controller layer without needing to add a reference to our MVC application.
However, our service layer needs to be able to pass validation error messages back to the controller layer. How can we enable the service layer to communicate validation error messages without coupling the controller and service layer? We can take advantage of a software design pattern named the Decorator pattern.
A controller uses a ModelStateDictionary named ModelState to represent validation errors. Therefore, you might be tempted to pass ModelState from the controller layer to the service layer. However, using ModelState in the service layer would make your service layer dependent on a feature of the ASP.NET MVC framework. This would be bad because, someday, you might want to use the service layer with a WPF application instead of an ASP.NET MVC application. In that case, you wouldn t want to reference the ASP.NET MVC framework to use the ModelStateDictionary class.
The Decorator pattern enables you to wrap an existing class in a new class in order to implement an interface. Our Contact Manager project includes the ModelStateWrapper class contained in Listing 7. The ModelStateWrapper class implements the interface in Listing 8.
Listing 7 - Models.cs
[!code-csharpMain]
1: using System.Web.Mvc;
2:
3: namespace ContactManager.Models.Validation
4: {
5: public class ModelStateWrapper : IValidationDictionary
6: {
7: private ModelStateDictionary _modelState;
8:
9: public ModelStateWrapper(ModelStateDictionary modelState)
10: {
11: _modelState = modelState;
12: }
13:
14: public void AddError(string key, string errorMessage)
15: {
16: _modelState.AddModelError(key, errorMessage);
17: }
18:
19: public bool IsValid
20: {
21: get { return _modelState.IsValid; }
22: }
23: }
24: }
Listing 8 - Models.cs
[!code-csharpMain]
1: namespace ContactManager.Models.Validation
2: {
3: public interface IValidationDictionary
4: {
5: void AddError(string key, string errorMessage);
6: bool IsValid {get;}
7: }
8: }
If you take a close look at Listing 5 then you’ll see that the ContactManager service layer uses the IValidationDictionary interface exclusively. The ContactManager service is not dependent on the ModelStateDictionary class. When the Contact controller creates the ContactManager service, the controller wraps its ModelState like this:
[!code-csharpMain]
1: _service = new ContactManagerService(new ModelStateWrapper(this.ModelState));
Summary
In this iteration, we did not add any new functionality to the Contact Manager application. The goal of this iteration was to refactor the Contact Manager application so that is easier to maintain and modify.
First, we implemented the Repository software design pattern. We migrated all of the data access code to a separate ContactManager repository class.
We also isolated our validation logic from our controller logic. We created a separate service layer that contains all of our validation code. The controller layer interacts with the service layer, and the service layer interacts with the repository layer.
When we created the service layer, we took advantage of the Decorator pattern to isolate ModelState from our service layer. In our service layer, we programmed against the IValidationDictionary interface instead of ModelState.
Finally, we took advantage of a software design pattern named the Dependency Injection pattern. This pattern enables us to program against interfaces (abstractions) instead of concrete classes. Implementing the Dependency Injection design pattern also makes our code more testable. In the next iteration, we add unit tests to our project.
|