Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I register ViewModels in Container?

Should I register ViewModels in Container and resolve from there?

Benefits:

  1. I can perform some actions when view model is activated
  2. Container will inject dependencies for me
  3. ???

Drawbacks:

  1. 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
  2. ???

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.

like image 404
Konstantin Spirin Avatar asked Oct 22 '10 09:10

Konstantin Spirin


1 Answers

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 InstancePerDependency with 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 :-)

like image 186
Bryan Watts Avatar answered Sep 28 '22 10:09

Bryan Watts