Your very first steps towards becoming a DI IoC Ninja

This is an introduction in getting started using the IoC (Inversion of Control) Container Framework Ninject for DI (Dependency Injection). We will focus on how to get started and not dig deeper into advanced (covered in future blog posts) areas or complicate things more than necessary while you still learn how to crawl like a ninja.

DI (Dependency Injection) & IoC (Inversion of Control)

DI from an object oriented programming perspective is a technique to make your applications components require it’s dependencies to be passed (injected) from the outside. This is accomplished by not specifying a specific implementation inside the components, instead only the type of service they need in form of a contract. This technique assists in avoiding tightly coupled classes.

An IoC Container can support you in this work and make it easier to change and extend your beloved application architecture. Ninject is the pick of this blog post but there are numerous of IoC Containers, just to name a few:

Ninject

What makes Ninject different than other IoC Containers? The following statement can be read at the Ninject homepage:

“An obsessive focus on simplicity and ease of use. We’ve seen the value of dependency injection, but were frustrated by the complexity of existing solutions. The goal of Ninject is make dependency injection accessible to all developers and all projects.”

This philosophy together with the amusing Ninja influences and lot of extensions make the open source project Ninject worth looking into.

Hello Ninja – as easy as One, Two, Three

Let’s visit the Dojo for some coding. We will create a simple entertaining application and use Ninject for some DI.

1 Fire up Visual Studio 2010 and create a new c# Console Application project.

2 Use NuGet and add the latest Ninject core package to your project.

NuGet is a Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects that use the .NET Framework. Please spend five minutes and learn how to use NuGet if it is new to you.

3 Type or paste in the following code in Program.cs

using System;
using Ninject;
using Ninject.Modules;

namespace NinjaFirstSteps
{
    interface IInstrument
    {
        void Play(string song);
    }

    class Flute : IInstrument
    {
        public void Play(string song)
        {
            Console.WriteLine("Played the {0} song using a flute", song);
        }
    }

    class Synthesizer : IInstrument
    {
        public void Play(string song)
        {
            Console.WriteLine("Played the {0} song using a synthesizer", song);
        }
    }

    class Entertainer
    {
        private readonly IInstrument _instrument;
        public Entertainer(IInstrument instrument)
        {
            _instrument = instrument;
        }
        public void Play(string song)
        {
            _instrument.Play(song);
        }
    }

    class EntertainerModule : NinjectModule
    {
        private readonly bool _existPower;
        public EntertainerModule(bool existPower)
        {
            _existPower = existPower;
        }

        public override void Load()
        {
            if (_existPower)
                Bind<Iinstrument>().To<synthesizer>();
            else
                Bind<Iinstrument>().To<flute>();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            bool existPower = false; // toggle this manually to change instrument

            IKernel kernel = new StandardKernel(new EntertainerModule(existPower));
            Entertainer musician = kernel.Get<entertainer>();
            musician.Play("I'm gonna flip out like a ninja");
            Console.ReadKey();
        }
    }
}

Start the application and enjoy the DI music.

Come again?

Let’s dissect the application to understand what’s going on.

Bindings

The EntertainerModule class is used to register all our dependencies by using type bindings to map a service type with an implementation type. Ninject’s fluent interface let you perform this type-safe and with the help of IntelliSense. The following binding tells Ninject to resolve an instance of Synthesizer and inject it when it encounters a dependency on IInstrument.

Bind().To();

I added a hardcoded flag named ”existPower” to decide what instrument will be injected. Feel free to change it to toggle between flute and synthesizer.

Kernel

The Program class is used to create a kernel to be used as a repository for requesting instances of the types we registered.

IKernel kernel = new StandardKernel(new EntertainerModule(existPower));
Entertainer musician = kernel.Get&lt;Entertainer&gt;();

Summary

Ninject comes with many more features than described here but hopefully by now, you are a few steps closer to becoming a DI IoC Ninja. I will continue to evaluate Ninject and probably return with more advanced and complex scenarios.

You can find more info about Ninject here:

 

Happy Ninjecting!

Trackback URL: https://codeblog.silfversparre.com/2011/05/your-very-first-steps-towards-becoming-a-di-ioc-ninja/trackback/