How to use Dependency Inversion to loosen the coupling? - Part 5
Dependency Inversion is explained with layered and multi-implementation examples, dependency injection, IoC containers, testing benefits and a summary of all the principles.
How to use Dependency Inversion to loosen the coupling? - Part 5
In most of the layered applications, the controller creates the service, the service creates the repository and the repository talks to the database. It looks natural, because the high level code uses the low level code to get the work done. But it means the business rules, which are the most valuable part of the system, depend on the database, the mail server and the file system, which are the details and change most often. We can’t test a business rule without the database, and we can’t change the database without touching the business rules. In the previous article, we discussed the Liskov Substitution Principle and the Interface Segregation Principle. In this article, we are going to see the last SOLID principle, the Dependency Inversion Principle, the techniques to apply it, and a summary of the whole series.
Maintainable Code series:
- Why does code become hard to maintain? - Part 1
- How to keep the code simple and the objects in charge? - Part 2
- What are the Single Responsibility and Open Closed principles? - Part 3
- What are the Liskov Substitution and Interface Segregation principles? - Part 4
- How to use Dependency Inversion to loosen the coupling? - Part 5 (this article)
TL;DR Summary
- Dependency Inversion Principle (DIP) - High level modules should not depend on low level modules, both should depend on abstractions. Abstractions should not depend on details, details should depend on abstractions.
- The “inversion” is that the low level code now depends on an abstraction which is owned by the high level code.
- Dependency Injection (DI) - Give the dependencies to a class from outside, mostly through the constructor.
- Inversion of Control (IoC) - The framework or the container controls the creation and the flow, not our class.
- Use the Factory pattern, a Service Locator or an IoC container to put things together at one place (the composition root).
- Benefits - Less coupling, high cohesion, reusability and easy testing.
Dependency Inversion Principle
What is it?
The Dependency Inversion Principle has two parts,
- High level modules should not depend on low level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
The high level module is the one which has the business rules, like a FundService. The low level module is the one which does the technical work, like reading from SQL Server or sending an email. In simple terms, don’t write new SqlFundRepository() inside the business code. Depend on an interface, and let somebody else decide which implementation to give.
A small word of caution on the name. Dependency Inversion (the principle), Dependency Injection (a technique to give the dependencies from outside) and Inversion of Control (the idea that something else controls the flow) are three related but different things. The principle tells what to achieve, and the other two help to achieve it.
Variation 1 - Layers
The first variation is the classic layered application, Controller, Service and Data Access. In the following diagram, the left side is the usual way, where each layer depends directly on the layer below it. The right side is the inverted way.

Find below the usual way,
public class FundController : Controller
{
private readonly FundService _service = new FundService();
public ActionResult Details(int id)
{
return View(_service.GetFund(id));
}
}
public class FundService
{
private readonly FundRepository _repository = new FundRepository();
public Fund GetFund(int id) { return _repository.Find(id); }
}
The controller creates the service, and the service creates the repository. To test the FundService, we must have a SQL Server database. If we change the repository constructor to take a connection string, the service must change, and then the controller must change. A change at the bottom travels all the way to the top.
Now the inverted way. Each layer depends on an abstraction, and the abstraction is owned by the layer above, because the layer above knows what it needs,
public interface IFundRepository
{
Fund Find(int id);
}
public interface IFundService
{
Fund GetFund(int id);
}
public class FundService : IFundService
{
private readonly IFundRepository _repository;
public FundService(IFundRepository repository) { _repository = repository; }
public Fund GetFund(int id) { return _repository.Find(id); }
}
public class FundController : Controller
{
private readonly IFundService _service;
public FundController(IFundService service) { _service = service; }
public ActionResult Details(int id)
{
return View(_service.GetFund(id));
}
}
The arrow of the dependency from the FundService to the repository is now inverted, the concrete FundRepository depends on (implements) the interface which the service defined. The business code doesn’t know anything about SQL Server.
Variation 2 - Many implementations
The second variation is when the same abstraction has more than one implementation. Imagine the fund data is in SQL Server today, and the team wants to try a document database for the factsheets. Without the abstraction, the service must know both,
public Fund GetFund(int id)
{
if (_useNoSql)
return new NoSqlFundRepository().Find(id);
return new SqlFundRepository().Find(id);
}
Every new database means editing the FundService again (it breaks the Open Closed Principle), and the service can’t be tested without both of them. With the abstraction,

public class SqlFundRepository : IFundRepository { /* ... */ }
public class NoSqlFundRepository : IFundRepository { /* ... */ }
The FundService doesn’t change at all. A new database is a new class which implements IFundRepository, and the selection is done at one place outside the service.
Techniques to apply it
Dependency Injection
Give the dependencies to the class from outside. There are three ways, constructor injection, property injection and method injection. Prefer the constructor injection, because the dependencies are visible and the object can’t be created in an invalid state. Use the property injection only for the optional dependencies.
Factory pattern
If a class must create the objects at runtime, for example a different repository for each request, ask a factory (IFundRepositoryFactory) which returns the abstraction. The class depends on the factory interface and not on the concrete classes.
Service Locator
A Service Locator is a registry from which the class asks for its dependencies, Locator.Get<IFundRepository>(). It is simple, but the dependencies are hidden inside the methods, so you can’t see them from the constructor, and a missing registration fails at runtime. Be mindful, use it only where the injection is not possible, for example in some legacy framework code.
Inversion of Control container
An IoC container like Unity, Ninject or Castle Windsor creates the whole object graph for us, based on the registrations. In ASP.NET MVC 3, you can register the container as the dependency resolver of the framework, so the controllers get their dependencies through the constructor automatically.
var container = new UnityContainer();
container.RegisterType<IFundRepository, SqlFundRepository>();
container.RegisterType<IFundService, FundService>();
// set the container as the MVC dependency resolver in Application_Start,
// using DependencyResolver.SetResolver(...) with your container adapter
The one place where all of these registrations are done is called as the composition root, and it is the only place which is allowed to know all the concrete classes.
Note: A container is a convenience, not a requirement. You can follow the DIP with plain constructor injection and by wiring the objects by hand at the start of the application. Start with that, and add a container when the wiring becomes painful.
Testing benefit
Because the FundService receives the IFundRepository, a test can give a simple fake and no database is needed,
public class FakeFundRepository : IFundRepository
{
public Fund Find(int id) { return new Fund { Id = id, Name = "Test Fund" }; }
}
[Test]
public void GetFund_ReturnsTheFundFromTheRepository()
{
var service = new FundService(new FakeFundRepository());
var fund = service.GetFund(7);
Assert.AreEqual(7, fund.Id);
}
This is the main reason why DIP is the base of the unit testing and the Test Driven Development (TDD), which we are going to discuss in the next series.
Benefits
- Less coupling and high cohesion.
- Reusability, the high level code can be used with any implementation.
- Easy testing.
Must Consider: Don’t create an interface for every class just because the principle says so. Create the abstraction where there is a real boundary, like a database, a web service, a mail server or a place where more than one implementation is likely. An interface with exactly one implementation and no reason to change is only noise (YAGNI).
Putting it all together
Find below the summary of all principles of this series, in the order we discussed,
| Principle | One line summary | How it helps maintenance |
|---|---|---|
| KISS, DRY, YAGNI | Keep it simple, one place for every rule, build only what is needed | Less code to read and change |
| Tell, Don’t Ask | Tell the object what to do | The logic is near the data |
| Law of Demeter | Talk only to your friends | The changes stay local |
| Single Responsibility | One reason to change | High cohesion |
| Open Closed | Extend without modifying | Lower regression risk |
| Liskov Substitution | Children keep the parent’s promise | Safe polymorphism |
| Interface Segregation | Small, cohesive interfaces | No unused dependency |
| Dependency Inversion | Depend on abstractions | Low coupling and easy testing |
All of them are different views of the same goal, high cohesion and low coupling, which we started with in Part 1. These are guidelines and not laws, so apply them when they remove a real pain and always balance them with KISS and YAGNI.
What is next?
Knowing the principles is the first step. In the next sessions of the TDD Boot Camp, we will go through,
- Clean Code - the practices to make the code readable, like naming and small methods.
- Refactoring - how to improve the design of the existing code safely, in small steps.
- Unit Test - how to write fast and reliable tests, using the fakes we saw in this article.
- Test Driven Development (TDD) - how to write the test first, and let the design come out of it.
Wrap up
In this article, we have looked at the Dependency Inversion Principle, its two variations, the techniques to apply it, and the summary of all principles of the Maintainable Code series. I really appreciate that you took the time to read this series. In the next series, I will walk you through clean code and refactoring, to apply these principles on the existing code.
Related Posts
How to keep the code simple and the objects in charge? - Part 2
KISS, DRY and YAGNI keep the code simple, while Tell Don't Ask and the Law of Demeter keep the logic near the data, explained with mutual fund redemption and NAV examples.
What are the Liskov Substitution and Interface Segregation principles? - Part 4
Liskov Substitution and Interface Segregation are explained with open-ended funds and fixed maturity plans, including the warning signs of a broken hierarchy and how to fix it.
What are the Single Responsibility and Open Closed principles? - Part 3
The Single Responsibility and Open Closed principles are explained with a mutual fund service and exit load rules, with the benefits, techniques and trade-offs of each.