1

I am building an WPF application using the MVVM Light Toolkit and specifically SimpleIoc.

I have a parent viewmodel that dynamically creates child viewmodels. When doing this I am using "standard" dependency injection to pass a IConfigService as a parameter to the constructor. I want the IConfigService to be a unique instance for each child viewmodel. So I try this:

IConfigService service = SimpleIoc.Default.GetInstance<IConfigService>(key);
ChildViewModel vm = new ChildViewModel(service);

Where key is a unique identifier for each child viewmodel. According to the documentation of MVVM Light and SimpleIoc this GetInstance method:

...provides a way to get an instance of a given type corresponding to a given key. If no instance had been instantiated with this key before, a new instance will be created.

There is also a remark that the class must have been registered before, else it returns null. In my case it has been, in ViewModelLocator:

var configService = new ConfigService();
SimpleIoc.Default.Register<IConfigService>(() => configService);

However, the GetInstance call returns the same instance every time.

What am I doing wrong here?

1 Answers1

0

You registered an already instantiated object.

SimpleIoc does not create its own instances with this overload. It always returns configService. Either you need to perform the instantiation within the lambda, because you are using a factory overload, or you can do this more easily by just passing the ConfigService type. SimpleIoc will take care of the instantiation itself.

Creepin
  • 482
  • 4
  • 20