I am strapping up a small WPF Application with MVVM and Ninject for DI (for the first time).
Creating my "Single Instance" ViewModels for the static UI Elements is easy going. But I am struggling with the ViewModels which are created on demand, e.g. on user actions, which cannot be injected, but have to be created - somehow- in the class itself.
The easiest way would be injecting the Ninject Kernel or make it globally available, but I believe thats bad practice.
While searching for a solutions, I strumbled on these two:
ViewModelLocator: I think it is more for the "Single Instance" ViewModels and because I am using DataTemplates to hook up the ViewModel with the View (ViewModel first), I am feeling its not the right way, but maybe I will integrate it for my singletons (if it does make sense with using WPF DataTemplates?).
Factory Pattern: I read about using an Abstract Factory for Object creation and just injecting the Factory into the ViewModels, which then can use it to create the dynamic ViewModels on demand. Sounds pretty easy and thats why I am in doubt, if its just relocating the problem?
So basically I am trying to get an Instance of an ViewModel Object by the Ninject Kernel deep down in the ViewModel Tree, e.g. triggered by an user event. Because I am using an Event Broker for Ninject, the Event Broker is only hooked up for Objects created by Ninject. Thats why I need my ViewModels created/injected by Ninject.
new InnerVM()
yourself ifInnerVM
has not many dependencies or youInnerVMFactory.Create()
it, which is cleaner. YourOuterVM
will then have a dependency onInnerVMFactory
. – Markus Hütternew InnerVM()
. Its dependencies are whatever DependenciesInnerVM
has and it provides these to theInnerVM
in everyCreate()
– Markus Hütter