views:

175

answers:

1

I'm new to IoC/DI frameworks. The first one I am trying is the Ninject framework. It seems straightforward, but I can't get my console application to run. I keep getting an ActivationException stating:

"Error activating MainWindow: the StandardProvider returned an instance of type FutureRealisticDateManager, which is not compatible with the requested service.
Using default binding from MainWindow to FutureRealisticDateManager (via StandardProvider)
     declared by DateBindingModule.Load()
Activation path:
  1) active request for MainWindow
     from Program.Main()
     using default binding from MainWindow to FutureRealisticDateManager (via StandardProvider)
     declared by DateBindingModule.Load()"

My code is very simple. Here is my Program file...

class Program
{
    static void Main(string[] args)
    {
        IKernel k = new StandardKernel(new DateBindingModule());


        MainWindow mw = k.Get<MainWindow>();
        mw.Show();
        Console.ReadLine();
    }
}

Here is my ninject binding module...

public class DateBindingModule : StandardModule
{
    public override void Load()
    {
        Bind<MainWindow>().To<FutureRealisticDateManager>();
    }
}

Here is the class that receives the injected class...

class MainWindow
{
    private IRealisticDateManager _d;

    [Inject]
    public MainWindow(IRealisticDateManager dateManager)
    {
        _d = dateManager;
    }

    public void Show()
    {
        Console.WriteLine("*** MainWindow [" + _d.GetRealisticDate().ToString() + "] ");
    }

}

And here is the actual class being injected...

public class FutureRealisticDateManager : TestNinject.IRealisticDateManager
{
    public DateTime GetRealisticDate()
    {
        return DateTime.Now.AddDays(15);
    }
}

And finally the simple interface that the injected class should implement...

public interface IRealisticDateManager
{
    DateTime GetRealisticDate();
}

Can anybody see what I am doing wrong?

+2  A: 

It fails because your binding is not right:

Bind<MainWindow>().To<FutureRealisticDateManager>();

FutureRealisticDataManager does not inherit from MainWindow. Instead you should write:

Bind<IRealisticDateManager>().To<FutureRealisticDateManager>();

This tells Ninject to return FutureRealisicDateManager whenever IRealisicDateManager is requested.

This way when you call k.Get<MainWindow>() kernel will inject FutureRealisticDateManager to the constructor.

jarek
Ah, that makes perfect sense. Thanks Mokosh!
willem