Search
Close this search box.

IoC in .NET part 3: Ninject 2 beta

I wanted to use Ninject 1.0 but I discovered that it didn’t support named binding, and didn’t know how to resolve multiple bindings to an array.

Luckily I found the Ninject 2 post it’s way better than the previous version, and the changes were almost a no brainer.

Hy, this continues the series of posts on IoC Containers in .NET. We are using these continers on a simple console application that autocompletes it’s functions. I’m mostly displaying the configuration part of the IoC, an overview of this tools will follow after we’ll have explored enough of them.

After a brief introduction of what is an IoC, I presented Autofac, and StructureMap.

In this post we’ll explore the Ninject 2 beta IoC that you can download at http://kohari.org/2009/02/25/ninject-2-reaches-beta/.

One thing that Ninject tries to do is free you from having to write an xml configuration file, that means it does not have support for such a configuration type, instead it comes with another nice fluent api.

What I do like about ninject it that it has support for .NET Compact Framework. I’m mentioning this because I had the occasion of writing an app for .NET CF and it helped me a lot. AFAIK this is the single IoC in .NET that has this support.

Instead of a container Ninject uses the notion of a kernel. Another difference is that it requires you to build modules, so I used the Bootstrap as a module, and the Components method returns the IKernel instance.

I didn’t explore the new Ninject deeply I was just happy I could get the application running.

So our Bootstrap class looks like this

public class Bootstrap : Module
    {
        public static IKernel Components()
        {
            IKernel kernel = new StandardKernel( new Bootstrap() );
            return kernel;
        }

        public override void Load()
        {
            Bind<IWriteString>()
                .To<ConsoleWriteString>()
                .InSingletonScope();
            Bind<IClearScreen>()
                .To<ConsoleClearScreen>()
                .InSingletonScope();

            Bind<IFunctionState>()
                .To<AlarmFunctionState>().Named("Alarm");
            Bind<IFunctionState>()
                .To<NewLineFunctionState>().Named("NewLine");
            Bind<IFunctionState>()
                .To<CalculatorFunctionState>().Named("Calculator");

            this.Bind<IConsoleInputService>().To<ConsoleInputServiceImpl>();

        }
    }

Don’t know about you but I like it. Obviously the way I get these values in the Program.cs changed as in the other posts but I didn’t expose that change.

Since Ninject doesn’t provide a Xml configuration you’re stuck with a codebase that nees to be recompiled, luckily that should not take to much.

As always the code can be downloaded here.

This article is part of the GWB Archives. Original Author: Sharpoverride

Related Posts