Harald
Harald

Reputation: 1037

Ninject 3: How to use Named Bindings with Modules?

I am new to Ninject (using the latest v3). I got the basics working fine (incl. named bindings without modules, i.e. on the kernel directly) but I can't get it to work with Modules.

The module looks like this:

public class MainModule : NinjectModule
{
    public override void Load()
    {
        Bind<Window>().ToMethod(context => App.Current.MainWindow).Named("MainWindow");
    }
}

And I am using it like this:

    public MainViewModel Main
    {
        get
        {
            return kernel.Get<MainViewModel>("MainWindow");
        }
    }

which results in an ActivationException telling me that "no matching bindings are available". Without the named binding it works fine.

How do I use named bindings with modules?

Upvotes: 0

Views: 494

Answers (1)

Remo Gloor
Remo Gloor

Reputation: 32725

You are binding Window but request a MainViewModel. There is no correlation between these two things. So I have no iead why you think this should work.

Without the name it works because self bindable objects like MainViewModel are implicitly bound to themself. That's why it is working.

Update:

If I understand you correctly then you want

Bind<Window>().ToMethod(context => App.Current.MainWindow).WhenParentNamed("MainWindow");
Bind<MainViewModel>().ToSelf().Named("MainWindow");

Upvotes: 1

Related Questions