chapter six

6 Async, Test-Driven Development and dependency injection

 

This chapter covers

  • Using locks, mutexes, and semaphores
  • Awaiting asynchronous methods
  • Using dependency injection with unit tests

In chapters 3 and 4, we looked at the codebase we inherited and discussed potential improvements. To solve the issues found, we started a new version of the Flying Dutchman Airlines service in chapter 5. We implemented the database access layer with Entity Framework Core in chapter 5. In this chapter, we start implementing the business logic by moving into the repository layer and creating the CustomerRepository class.

Figure 6.1 After having implemented the database access layer in chapter 5, we move on to implementing the CustomerRepository in this chapter.

The repository layer is the meat and potatoes of our service. In the repository layer we do two things:

  1. Query and manipulate the database by communicating with the database access layer
  2. Return the requested entities or information to the service layer

We want to create isolated, small, clean, and readable methods that follow the Single Responsibility Principle (SRP). Following the SRP makes it easier to test and maintain our code because we can quickly understand every method and fix any potential bugs.

6.1   Test-Driven Development

6.1.1   Exercises

6.2   The CreateCustomer method

6.2.1   Why you should always validate input arguments

6.2.2   Using “Arrange, Act, Assert” to write unit tests

6.2.3   Validating against invalid characters and LINQ

6.2.4   In-lining test data with the [DataRow] attribute

6.2.5   Object initializers and auto-generated code

6.2.6   Constructors, reflection, and asynchronous programming

6.2.7   Locks, mutexes, and semaphores

6.2.8   Synchronous to asynchronous execution… continued

6.2.9   Dependency Injection and testing Entity Framework Core

6.2.10   Exercises

6.3   Summary