简体   繁体   中英

MVVM Light ViewModelLocator: How to register Singleton ViewModel?

I'm familiar with MVVM Light toolkit's ViewModelBase, Message, but not familiar with the ViewModelLocator. In my application there is Singleton ViewModel, such as PrinterViewModel. Registering is like

SimpleIoc.Default.Register<IPrinter,PrinterViewModel>();

When debugging, the error is something like 'Cannot register: No public constructor found'.

So 2 questions:

  1. Is it bad idea to have Singleton ViewModel?
  2. How to register Singleton ViewModel, since I did not find any overloads to pass an instance for certain interface?

1) As a general rule of thumb, yes. It's the job of the injection framework to set scoping. You might have a database repository class (say) that needs per-form scoping in WPF builds (so the user can cancel the edit), per-request scoping in web builds and singleton scoping in command-line tools. Neither the class itself nor any of its consumers should be aware of what scoping that object has been given.

2) A simple (and not very good) solution would be to just add the singleton instance to your ViewModelLocator and always return that. Another one is to just call GetInstance() without a key and rely on lazy creation. I'm not a huge fan of SimpleIoC though, it's a bit too simple for my liking. Try taking a look at more fully-featured frameworks like Ninject, you'll find they're much more flexible and fluent in their usage eg:

Bind<IPrinter>().To<PrinterViewModel>().InSingletonScope();

I had a case where I wanted to register a singleton by myself, because I needed to give an argument to the object constructor.

I then registered the singleton instance by doing:

SimpleIoc.Default.Register<IInterface>(() => new ImplementationClass(param));

The object will be constructed only once, the first time that this line is called:

ServiceLocator.Current.GetInstance<IInterface>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM