Intro to Dependency Injection 7


A few weeks ago I had to privilege to present at the St Pete .NET Meetup in St. Petersburg Florida. The topic I chose is an important and interesting topic, at least in my mind. The presentation was well received, so I thought I might post an article here for a broader audience.

What exactly is Dependency Injection (DI) anyway? The great and powerful Wikipedia lists Dependency Injection as:

In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

So what does that mean? Basically, we require a means to invert the relationship between objects within our systems.

Martin Fowler says:

The basic idea of the Dependency Injection is to have a separate object, an assembler, that populates a field in the [target] class with an appropriate implementation for the finder interface.

It loses a bit out of context, but the linked article is well worth the read.

Let’s look at some code.

In our first example, we’ve got a file=>new project, ASP.NET MVC in this case. Messages are hard coded in our controllers. Nothing fancy here.

In our next example we’ve got the beginnings of some logical separation. It’s still a simple file=>new MVC project, but we’ve got a Service handling the retrieval of the message for the actions in our controller. We’ll pretend that our service is hitting a database or something more interesting for our sample purposes.

The problem here is that our HomeController now depends on the concrete implementation of the SampleService. This makes our code independently untestable. Every time you see the new keyword this is an indication that some refactoring may be needed.

For a first refactoring, you may choose to move the declaration out to a field level service and new-up the SampleService in the constructor, seen here:

This may be a little cleaner, but still has the same inherent flaws as our previous example.

One method of DI, “Poor Man’s Dependency Injection” doesn’t require any additional frameworks to install. Let’s take a look:

Here we’ve got an additional constructor that accepts an Interface. This allows us remove the dependency on the concrete implementation of the SampleService. You may have noticed we’ve also added to our default constructor, the instantiate a new SampleService if one is not supplied. This allows us to supply our own implementation for testing purposes, should the need arise.

You can see in our next example that this will work through multiple levels of our system:

Now, I’m not a fan of this method. It’s ugly and a bit confusing when you first see it. There are better, more readable options available to us.

 

Unity

Unity languished under Microsoft for a number of years. Thankfully it’s under new control now and seems to have had new life breathed into it. Unity offers a feature rich, highly configurable option for DI.

For our purposes we’ll install the nuget package, Unity.Mvc. Open the UnityConfig.cs file located in the App_Start folder and register our types.

Now we don’t need our Poor Man’s constructor anymore. Everything is much cleaner now.

Read more on Unity, here.

 

Ninject

I like Ninject for a lot of reasons. One of which, of course, is their fancy ninja guy. Ninject isn’t quite as feature rich as Unity, but offers more in way of performance. Some speed tests I’ve seen have Ninject operating at nearly twice the speed of Unity in some instances. Configurations in code are similar to Unity as well. Let’s install the nuget package, Ninject.MVC5, and take a look at the NinjectWebCommon.cs file.

For more on Ninject, and their neat little ninja guy, click here.

 

Autofac

Perhaps the most performant DI framework is Autofac. Boasting the fastest speeds in most available tests, this also happens to be my favorite. I also believe they have the best, most comprehensive collection of online documentation.

I haven’t found a nuget package that includeds a config file, so we’ll start with the Autofac.Mvc5 package and then make our own AutofacWebCommon.cs file.

More on Autofac, and their awesome documentation, can be found here.

###

But, I want to hear from you out there. What are your favorite DI/IoC frameworks?  What tips and tricks do you have for those new to DI?

Source and slidedeck can be found here.

 

A Microsoft MVP, John has been a professional developer since 1999. He has focused primarily on web technologies and has experience with everything from PHP to C# to AngularJS to SignalR. Clean code and professionalism are particularly important to him, as well as mentoring and teaching others what he has learned along the way.

Please Consider Sharing This Post:

Facebooktwittergoogle_plusredditlinkedinFacebooktwittergoogle_plusredditlinkedin
  • tugando

    How about Spring.Net?

    • Spring.Net was rated Very Slow in the post linked by Jay above. That said, I’m not sure that Dependency Injection Containers speed should be the biggest concern for most applications. If you’re having speed concerns in your application, DI is likely not the culprit. Use what you know, learn to abstract, and switch if you feel pain.

      • tugando

        Spring in king of the IoC frameworks for Java, but it looks like support for Spring.Net has fallen significantly. This could be why the .Net version of Spring has failed to impress.

  • dombijd

    What do you think about the MS solution (MEF): https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx

  • Jay

    Simple Injector. It’s simple, forces a single constructor and has good performance in comparison to others.

    http://www.palmmedia.de/blog/2011/8/30/ioc-container-benchmark-performance-comparison

    • I’ve been reading a lot of great things about Simple Injector in the past few weeks. I think I’ll incorporate this into my presentation from now on.