What is Dependency injection?

Dependency injection is a technique used for resolving dependencies by using inversion of control, it helps you write better code and makes your code more testable in Unit Tests.

What is a Unit Test?

A unit test is a small method which is set up to call some of the code you have written and check the outcome against what your were expecting it to return.

Here is an example unit test taken from an open source project called Rework, which Luke Warren created.

using NUnit.Framework; using Rework; using System; namespace UnitTests { [TestFixture] public class RangeTests { [Test] public void Before_WithDateBefore_ReturnsTrue() { var dateToCheck = new DateTime(2016, 01, 01); var dateToUse = new DateTime(2016, 01, 02); bool result = Range.Before(dateToCheck, dateToUse); Assert.IsTrue(result); } } }

Why do we need Dependency Injection?

If your code relies on a service outside of your class, like the MembersService in Umbraco, you can't test the code properly in a unit test. You don't have control over the MembersService and you have to rely it running and being available at the time of calling. Your unit test will be in a separate library to your web application so it won't have the same context.

OK, you've convinced me. How do I set it up?

Watch this video to see me setting it up live with the help of my friend Luke Warren from South Africa

Watch on YouTube