I've been building a WPF application. Up till now, most ViewModels worked strictly off their own code.
I recently decided to create a base class "ApplicationViewModel
" migrate common code into it. For the Most part this works fine, but I've run into an issue I'm having difficulty with.
It appears that my inheriting viewmodels are spawning their own instance of this base viewmodel. As a result; should a method in ClassA change a variable in the base class, then ClassB still registers the very same variable as null, or whatever it's previous value was.
Initially I thought registering the instance in Microsoft's Unity container would solve the issue,
public App()
{
Container.RegisterType<ApplicationViewModel>(new ContainerControlledLifetimeManager());
}
but that changed nothing.
The obvious answer I found after research was to turn the class static, but I would prefer another solution before I head that route. Too much of my programs functionality may require reworking.
I'm not sure if a singleton Instance Property can even work with base class declarations.
So I suppose my question is: How would I ensure the same instance of this viewmodel base class is used throughout all my ViewModels?
How would I ensure the same instance of this viewmodel base class is used throughout all my ViewModels?
Not possible. A base class is part of the definition of the class that inherits from it, i.e. the base class and the derived class are part of the very same instance. When you create an instance of the dervived class, only a single instance of that type is created. And the base type is part of this type.
If you only want a single instance of the base class around inheritance is not the solution.
Instead you could get a reference to the shared view model object using the Container
from each of the child view models:
public class ChildViewModel //doesn't inhert from the base view model
{
public ChildViewModel()
{
var sharedViewModel = Container.Resolve<ApplicationViewModel>();
//call any properties or methods of the sharedViewModel...
}
}