Thursday, April 18, 2013

Ninject







I was once using IOC in one of my earlier projects back in 2007. "Castle Windsor" Now it's time to explore new dependency injectors. Ninject.

I am creating an admin tool for my current project. I want to explore new architecture, patterns and a testable loosely coupled application. So first goal is to setup a dependency resolution project which will help me decoupled my concrete classes from my client. To achieve this, here is a sample of code.

This is the entry point of my application. ILogger is the interface of my service that i will be using in my application. In this example, I used IKernel to create an instance of my ILogger to implement a specific implementation which is FileLogger.


using Infrastructure.Interfaces;
using Ninject.Modules;


public partial class App : Application
{
ILogger _logger;

protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            SingleInstance.Make();
            base.OnStartup(e);

            IKernel kernel = new StandardKernel(new LoggingModule(typeof(App).ToString(),   App.AppPath.ToString()));
            DependencyResolution(kernel.Get<ILogger>());

            CreateEntryWindow();                                  
            _logger.Info("Application started!");
        }

}


private void DependencyResolution(ILogger logger)
        {
            _logger = logger;
        }




------------------------------------------------------------------------------

using BackDoors.Logger;
using Infrastructure.Interfaces;
using Ninject.Modules;



public class LoggingModule: NinjectModule
    {      
        string _classObject;
        string _appPath;

        public LoggingModule(string classObject,string appPath="")
        {          
            _classObject = classObject;
            _appPath = appPath;
        }      

        public override void Load()
        {
            Bind<ILogger>().To<FileLogger>()
                .WithConstructorArgument("classObject", _classObject)
                .WithConstructorArgument("appPath", _appPath);
        }      
    }