0

right now I am using MVVM Light to achieve the MVVM Pattern. So in my view I create multiple tabs and bind them to multiple instances of one ViewModel. I achieve this with:

ServiceLocator.Current.GetInstance<ViewModel>(key);

When I do this, every instance of ViewModel is connected to the same one instance of DataService registered in the ViewModelLocator:

SimpleIoc.Default.Register<IDataService, DataService>();

But I want to have for every instance of the Viewmodel also one instance of Dataservice. Why? Because each instance of ViewModel has the same function but requires other data.

How do I create in MVVM Lights ViewModelLocator a new instance of DataService when for a new Instance of ViewModel? Is this possible or isn't that a good approach in the MVVM Pattern and I failed to understand DataService correctly?

3 Answers3

1

You can use the overloaded version of Register method to create multiple instances of the data service.

SimpleIoc.Default.Register<IDataService>(()=>new DataService(),"viewmodel1");
SimpleIoc.Default.Register<IDataService>(()=>new DataService(),"viewmodel2");
Sridhar
  • 837
  • 1
  • 10
  • 21
1

All the answers above did not work for me too, so i remastered them a bit.

You register your Data Service instance normally:

SimpleIoc.Default.Register<IDataService, DataService>();

Afterwards you insert factory method by registering your ViewModel instance to get a new Instance (and not the cached one) of your Data Service directly in the constructor of ViewModel:

SimpleIoc.Default.Register<ViewModel>(() => new ViewModel(SimpleIoc.Default.GetInstanceWithoutCaching<IDataService>()));
kostjaigin
  • 125
  • 2
  • 8
0

SimpleIoc will return the same cached instance, if you want a new fresh instance on every call, use one of the Register method overloads:

public void Register<TClass>(Func<TClass> factory) where TClass : class{}

So, in your case will be something like

SimpleIoc.Default.Register<IDataService>(() => new DataService());

EDIT- You're right, probably this answer will guide you in the right direction. I'd recommend you to use a full featured IOC container (I've used Autofac and SimpleIoc with success) where the lifestyle can be properly assigned.

Community
  • 1
  • 1
D.Rosado
  • 5,634
  • 3
  • 36
  • 56
  • Thanks for your answer but this doesn't work for me. The Constructor of class DataService is only called once. Calling the Register method outside the static constructor of ViewModelLocator throws an System.InvalidOperationException. – Sebastian Richter Jul 08 '15 at 15:26
  • Thanks for the tip with Autofac. Too bad it doesn't work in MVVM Light. – Sebastian Richter Jul 09 '15 at 07:00
  • @SebastianRichter Of course it works, you can use any IOC container. http://stackoverflow.com/a/10043357/787511 – D.Rosado Jul 09 '15 at 08:39