I’m learning about using Caliburn.Micro as a MVVM framework for a WPF application. In view X I want to show another view Y using ActivateItem. In this view Y, when the user clicks a button, I need to show another view Z as a dialog. So I need an instance of WindowManage in view Y.
This means that the WindowManage will have to be injected into viewmodel of Y, so I can use it to call windowManager.ShowDialog() for view Z.
So I was thinking that I should add a constructor into viewmodel of Y which accepts an IWindowManager parameter.
public YViewModel( IWindowManager windowManager) { ... }
Can Caliburn.Micro automatically inject the instance of the viewmanager into YViewModel? Without the WindowManage I would write
ActivateItem(new YViewModel());
but this won’t work when I need the WindowManage… how am I suppose to write ActivateItem when YViewModel needs an instance of the WindowManage?
Caliburn.Micro is no IoC container itself. Its built-in bootstrapper has a simple IoC implementation (rather a service locator) which cannot do dependency injection like you want to do with the
IWindowManagerconstructor parameter.Though your solution works it will only do so in the simple cases and it is also considered bad practice to call a service locator from your classes.
There are plenty of good IoC containers around. I would recommend having a look at Unity or Autofac. For both you will find adapted Caliburn.Micro bootstrappers on the internet.
In Autofac for example you would have a line like:
inside your custom Autofac bootstrapper. Whenever YViewModel gets instantiated through the IoC container the same instance of MyWindowManager would get injected.