Originally I had ChildUserControl
inside ParentUserControl
inside MainWindow
with this view-models (here only constructors):
public MainViewModel(IParentViewModel pvm) {}
public ParentViewModel(IChildViewModel cvm) {}
public ChildViewModel(IMessenger m) {}
And straightforward DI initialization in ViewModelLocator
:
var container = SimpleIoc.Default;
container.Register<IMessenger, Messenger>();
container.Register<IParentViewModel, ParentViewModel>();
container.Register<IChildViewModel, ChildViewModel>();
container.Register<IMainViewModel, MainViewModel>();
...
public IMainViewModel MainViewModel => ServiceLocator.Current.GetInstance<IMainViewModel>();
Then I needed to add second ParentUserControl
instance near the first one, and let them work independently. MainViewModel
constructor became to look like this:
public MainViewModel(IParentViewModel pvm1, IParentViewModel pvm2) {}
But DI initialization changed dramatically:
container.Register<IMessenger, Messenger>();
container.Register<IParentViewModel>(
() => new ParentViewModel(new ChildViewModel(container.GetInstance<IMessenger>("key1"))),
"key1");
container.Register<IParentViewModel>(
() => new ParentViewModel(new ChildViewModel(container.GetInstance<IMessenger>("key2"))),
"key2");
container.Register<IMainViewModel>(() => new MainViewModel(
container.GetInstance<IParentViewModel>("key1"),
container.GetInstance<IParentViewModel>("key2")));
As you can see, now I have to point to concrete ParentViewModel
and ChildViewModel
classes in several places, and I also have to manually use GetInstance
everywhere. I think this is not good.
What can you tell about this latter DI initialization? I guess it can't be improved by SimpleIoc, but can Unity or Ninject help in this situation?
public MainViewModel(ViewModelServiceLocator locator)
, wouldn't they? @t3chb0t \$\endgroup\$