2
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\begingroup\$ This is not DI but service locator. They work differently. \$\endgroup\$
    – t3chb0t
    Commented Sep 30, 2016 at 6:34
  • \$\begingroup\$ My view models receive interfaces for concrete entities, this is why I name it DI. In case of service locator, they would have to receive service locator instances, like public MainViewModel(ViewModelServiceLocator locator), wouldn't they? @t3chb0t \$\endgroup\$
    – Sam
    Commented Sep 30, 2016 at 7:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.