Should I register ViewModels in Container and resolve from there?
Benefits:
- I can perform some actions when view model is activated
- Container will inject dependencies for me
- ???
Drawbacks:
- ViewModel lifetime management can be tricky:
- if I make ViewModel singleton then I can’t instantiate several controls of the same type
- if I make ViewModel transient then I can easily end up in a situation of having several different instances when I actually expect same instance injected
- ???
What’s the right answer?
I’d prefer to register if I could mitigate lifetime drawback.
I’m using Caliburn and Autofac if it matters.
A container is an ecosystem inhabited by the objects it creates. View models interact with those inhabitants and thus are also part of the ecosystem. To accurately reflect that relationship, you should register view models in the container.
You should always use
InstancePerDependencywith view models. A view model represents the state and behavior of a particular piece of UI – it is the non-framework-specific analogue of a control. Just as you can’t generally place the same control instance in two locations in a UI tree, you can’t also reuse the same view model instance.If you could, we’d call it a
ViewsModel🙂