1
votes

I hope someone can shine some light on best practise for my usecase.

I am using mvvm light and the simpleIoC container in a wpf usercontrol. I register my model and view models, dataservice and designtime service to it (very much according to mvvm light sample code)

The SimpleIoC container usage examples that I have seen seems to always treat the container as static / global for GalaSoft namespace.

But if I would create two instances of my WPF control in the same application I of course want each user control to have its own set of VMs and Model instance. So basically its own set of SimpleIoC registered instances. How would I best accomplish that when the default IoC container seems to be a static object?

3

3 Answers

2
votes

When you getinstance you can optionally provide a key. Although you get a singleton per type by default this generates another cached version of that type per key. Meaning you could use a guid or something as a key per instance you require.

There's a potential problem though. If you getinstance 100 different versions then they're all in memory for the lifetime of your app.

You're probably ok if this is just going to be a few instances.

Any more and you're probably best using a more sophisticated di container. SimpleIoC is only intended for simple use cases.

You can, however, use a factory method when you getinstance. This is not to my taste, but if you really wanted to use simpleioc then it's something to consider.

You can read more from laurent bugnion here.

https://msdn.microsoft.com/en-us/magazine/jj991965.aspx

1
votes

That's what the factory pattern is designed to solve, you create a class that creates your control view models and you inject that instead.

Better separation of concerns too.

0
votes

How would I best accomplish that when the default IoC container seems to be a static object?

Don't use the default container but create your own instance of the SimpleIoc class:

User Control A:

SimpleIoc containerA = new SimpleIoc();
containerA.Register<ViewModel>();
...
ViewModel vm = containerA.GetInstance<ViewModel46>();

User Control B:

SimpleIoc containerB = new SimpleIoc();
...