0

现在我正在使用 MVVM Light 来实现 MVVM 模式。因此,在我看来,我创建了多个选项卡并将它们绑定到一个 ViewModel 的多个实例。我通过以下方式实现了这一目标:

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

当我这样做时,ViewModel 的每个实例都连接到在 ViewModelLocator 中注册的同一个 DataService 实例:

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

但我希望 Viewmodel 的每个实例也有一个 Dataservice 实例。为什么?因为 ViewModel 的每个实例具有相同的功能但需要其他数据。

当为 ViewModel 的新实例时,如何在 MVVM Lights ViewModelLocator 中创建 DataService 的新实例?这可能还是 MVVM 模式中的一个好方法,我未能正确理解 DataService?

4

3 回答 3

1

您可以使用Register方法的重载版本来创建数据服务的多个实例。

SimpleIoc.Default.Register<IDataService>(()=>new DataService(),"viewmodel1");
SimpleIoc.Default.Register<IDataService>(()=>new DataService(),"viewmodel2");
于 2015-07-09T10:21:02.597 回答
1

上面的所有答案也对我不起作用,所以我重新制作了一些。

您通常注册您的数据服务实例:

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

然后通过注册 ViewModel 实例来插入工厂方法,以直接在 ViewModel 的构造函数中获取数据服务的新实例(而不是缓存的实例):

SimpleIoc.Default.Register<ViewModel>(() => new ViewModel(SimpleIoc.Default.GetInstanceWithoutCaching<IDataService>()));
于 2019-12-20T14:09:54.397 回答
0

SimpleIoc 将返回相同的缓存实例,如果您希望每次调用都有一个新的实例,请使用 Register 方法重载之一:

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

所以,在你的情况下会是这样的

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

编辑-你是对的,可能这个答案会引导你朝着正确的方向前进。我建议您使用功能齐全的 IOC 容器(我已成功使用AutofacSimpleIoc),可以正确分配生活方式。

于 2015-07-08T14:04:30.917 回答