Dependency Injection with NInject

Here’s a demo I wrote to show how basic NInject code works.

I setup an abstraction of the IExample interface as the class Example. I’ll use this later to get my HelloWorld text.

I then use it in a Print object (which implements IPrint) and then call the HelloWorld function on the IExample object, whatever that is. Because I’ve already bound any requests for IExample to Example, I will get an Example object.

I initialise the NInject kernel here:

IKernel ninjectKernel = new StandardKernel();

I then add the NInject binding (mapping) here:

ninjectKernel.Bind<IExample>().To<Example>();

If I didn’t setup any binding, I’d get the following NInject.ActivationException:

Error activating IExample
No matching bindings are available, and the type is not self-bindable.
Activation path:
  1) Request for IExample

I’ve posted a full Console Application example below:

using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ConsoleApplication1
{
    // Example interface
    public interface IExample
    {
        string HelloWorld { get; }
    }

    // Example implementation
    public class Example : IExample
    {
        public string HelloWorld
        {
            get
            {
                return "Hello world";
            }
        }
    }

    // print interface for abstraction
    public interface IPrint
    {
        string PrintFunction();
    }

    // print implementation
    public class Print : IPrint {

        private IExample _example;

        public Print(IExample exampleParam) {
            _example = exampleParam;
        }

        public string PrintFunction() {
            return _example.HelloWorld;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            // declare the kernel for ninject
            IKernel ninjectKernel = new StandardKernel();

            // setup the example binding
            ninjectKernel.Bind<IExample>().To<Example>();

            // get an implementation (loosely coupled)
            IExample exampleInstance = ninjectKernel.Get<IExample>();

            // return the value and print to the console
            IPrint example = new Print(exampleInstance);
            Console.WriteLine("result: " + example.PrintFunction());
            Console.ReadLine();

        }
    }
}