1
votes

I'm getting into Ninject. Simplifying my real scenario, I have a class A with property injection:

public class NinjectBindings : NinjectModule
{
    public override void Load()
    {
        Bind<IMasterViewModel>().To<IQMasterViewModel>();
    }
}

public class A
{
    [Inject]
    public IMasterViewModel _viewModel
    {
        get;
        set;
    }

    public A()
    {
    }
}

And a class B that instantiate A via default constructor:

public class B
{
    public A a = new A();
}


Ninject.IKernel kernel = new StandardKernel(new NinjectBindings());
var b = kernel.Get<B>();

If I try to resolve class B using Ninject.kernell.Get() call the dependency of class A will not be injected into A instance. Can anyone suggest what is the correct way to handle such injection if I can't change the way object A is instantiated? Because in real scenario class B is a WPF Window and class A is a UserControl declared in XAML. Thanks.

2

2 Answers

1
votes

In order for A to have its dependencies injected it needs to be instantiated by Ninject.

When using IoC you should be passing in dependencies rather than instantiating in the class with new. Therefore you can fix this by passing A as a constructor argument to B instead of instantiating it yourself in the constructor.

public class B
{
    public A MyA;

    public B(A a)
    {
        MyA = a;
    }
}

Depending on how your classes are set up, you may need to create bindings or let them be self-bindable. I would suggest creating interfaces for A and B and binding these to the concrete types, as it makes the code much easier to test with a mocking framework.

Note that the binding you posted...

Bind<IMasterViewModel>().To<IQMasterViewModel>();

appears to be binding an interface to an interface rather than a concrete type, which is wrong.

1
votes

Class A doesn't have its dependencies injected, because is instantiated by you, not by your container.

I believe this is more about how to implement MVVM properly. See frameworks like Caliburn micro or Prism how to do it.