Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when using multiple constructors with Mvvm light and ViewModelLocator

Tags:

c#

wpf

mvvm-light

I'm facing this issue when having a ViewModel with multiple constructors in Mvvm Light:

I have a view model that has an empty ctor, and then i created a second one that receives a parameter (wanting to do something else in some cases ... ). If i try to run the application I'll get:

Cannot register: Multiple constructors found in Inner_VM but none marked with PreferredConstructor.

This happens only if i register the ViewModel in the Locator:

SimpleIoc.Default.Register<Inner_VM>();

and then use this in the property:

public Inner_VM Inner
{
    get { return ServiceLocator.Current.GetInstance<Inner_VM>(); }
}

If I omit the registration of the ViewModel, and then use this in the property:

public Inner_VM Inner
{
    get { return new Inner_VM(); }
}

everything seems to work ...

I thought the first option makes use of a static instance that is being reused, and the second just creates a new one everytime I use it. (it doesn't matter much in my app, but I'm trying to understand the why, and couldn't find anything to explain it, even after searching both S.O. & google for this issue).

Any help would be welcomed.

like image 230
Noctis Avatar asked Feb 19 '26 14:02

Noctis


1 Answers

you can put PreferredConstructorAttribute on your Default constructor to solve this issue.

like image 86
Nitin Avatar answered Feb 22 '26 04:02

Nitin