Home » .NET » Dependency Injection via Constructor Injection

Dependency Injection via Constructor Injection

The most common way of implementing Dependency Injection (DI) is to use Constructor Injection with classes. Let’s suppose we have a Customer class defined as follows:

We can create a service to fetch customer records and define an interface for this service:

An actual implementation of the DataService class could look like this:

Obviously the real thing would fetch the real records from somewhere, e.g. a database.

When we fetch these records we’d like to put them in a Customer repository. Whenever we create an instance of the CustomerRepository class we’ll pass in the dependency to the constructor. This is called “Constructor Injection”:

I’m going to use a DI container to setup my dependencies. There are many out there that you can use, but for this example I’m going to use Unity. There’s an article that descibes what I’m doing Microsoft Unity. Here’s how:

We can now use mock objects for unit tests and inject those instead of real instances. I’m going to use the Moq framework to mock my objects: