Dependency Injection and highly coupled objects

Coding Journeyman

power-plugI consider that Dependency Injection (DI) is a very helpful pattern, I love to use it in order to reduce the coupling in my code and it helps me when writing unit tests. But sometimes the code depends on objects that are difficult or impossible to mock.

The HttpContext class of the ASP .NET MVC framework is one example of this kind of object.

I created the following Controller and View as examples:

publicclass IndexController : Controller
{[HttpGet]public ActionResult Index(){string[] languages = HttpContext.Request.UserLanguages;return View(model:languages);}}
@model string[]
@{
    Layout = null;
}
 
<!--DOCTYPE html>
 
<html><head><metaname="viewport"content="width=device-width"/><title>Index</title></head><body>

View original post 759 more words

Dependency Injection to the rescue

Coding Journeyman

code-coupling

I am a developer, I believe in unit testing and I write a lot of them. But it was not always the case, mostly because I was working on a highly coupled code base. Whenever I wanted to test a single functionality I had to set up a lot of things (database, configuration files, …) to do so even if this functionality was not linked to these dependencies. It was spaghetti code into a big ball of mud.

Then I discovered the Dependency Injection (DI) pattern and it changed the way I designed my code and it made testing much easier. The DI purpose is to reduce coupling between software components in order to improve maintainability and testability. I created the following piece of code to demonstrate the principle :

publicclass User
{publicstring Name {get;set;}publicstring Email {get;set;}

View original post 848 more words

Blog at WordPress.com.

Up ↑