I’m creating a WPF app using Prism and Unity as the container. A couple of times I’ve come unstuck with the order of registering types whereby a type (ViewModel into View constructor) has been auto created by Unity when I’ve not registered it. Then I’ve tried to register the type using ContainerControlledLifetimeManager() and thought I’d created a singleton. However the auto creation has meant multiple instances of the view model.
Besides the obvious solution of not being a muppet and not doing the above, is there a way to prevent Unity auto creating unregistered types and perhaps throwing an exception instead?
Define an interface for each of your ViewModels and then register them accordingly.
In your constructor make sure that the interface type is being injected, not the concrete type as Unity will certainly construct an instance of a concrete type since it is resolvable; whereas an interface can have N implementations.
In addition, your code should be constructed in that the data that needs to exist across the application should come form a service, not the ViewModel. Making your ViewModel a singleton should not be your approach, proxy the data through a service. this way your ViewModel can be constructed/destroyed at will, the data you want persisted exists elsewhere.