Search code examples
c#wpfmvvmninjectviewmodellocator

Using ninject as a WPF view mode locator - viewmodels as singletons


I'm using ninject's kernel as a viewmodel locator in a WPF application.

The kernel helper class:

public static class IoCKernel
    {
        private static IKernel kernel;

        public static void Init(params NinjectModule[] modules)
        {
            if (kernel == null)
            {
                kernel = new StandardKernel(modules);
            }
        }

        public static T Get<T>()
        {
            return kernel.Get<T>();
        }
    }

And the ViewModelLocator exposes the Get method like:

public class ViewModelLocator : IViewModelLocator
    {    
        public MainWindowViewModel MainWindowViewModel
        {
            get
            {
                return IoCKernel.Get<MainWindowViewModel>();
            }
        }
    }

And when the instance is needed, it's called like:

IoCKernel.Get<IViewModelLocator>().MainWindowViewModel;

However, the IoCKernel.Get<MainWindowViewModel>() will always return a new instance. Is there a way to make it only work with one instance?


Solution

  • If you set up a binding in Ninject, you can call the InSingletonScope method:

    Bind<IYourInterface>().To<YourClass>().InSingletonScope();
    

    In your case (you do not have an interface for the view model) it might be:

    Bind<MainWindowViewModel>().ToSelf().InSingletonScope();
    


    See here for more info : Object Scopes in Ninject