Sebastian Richter
Sebastian Richter

Reputation: 485

MVVM Light create multiple instance of DataService

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?

Upvotes: 0

Views: 1543

Answers (3)

kostjaigin
kostjaigin

Reputation: 175

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>()));

Upvotes: 1

Sridhar
Sridhar

Reputation: 857

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");

Upvotes: 1

D.Rosado
D.Rosado

Reputation: 5773

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.

Upvotes: 0

Related Questions