【发布时间】:2011-06-25 17:15:18
【问题描述】:
我刚刚开始尝试使用 IoC 容器。目前,我正在使用本土工厂来构建我的 ViewModel,它有两种风格:单例和基于 id。换句话说,我的应用程序(根据定义)一次只有一个 Room,因此只有一个 RoomViewModel,但很多用户可以在那个房间里,所以我需要很多 UserViewModel。但我想确保,例如,对于 UserId="johnsmith" 的用户,只创建了一个 UserViewModel,并且任何检索该 UserViewModel 的尝试都将返回相同的实例。
我不知道这是否有助于解释或混淆它们,但这是我目前使用的方法:
public ViewModelType GetViewModelByKey<ViewModelType, KeyType>(KeyType key)
where ViewModelType : AlantaViewModelBase, new()
{
IDictionary dictionary;
var type = typeof(ViewModelType);
if (!keyedViewModelDictionaries.TryGetValue(type, out dictionary))
{
dictionary = new Dictionary<KeyType, ViewModelType>();
keyedViewModelDictionaries.Add(type, dictionary);
}
var viewModels = (Dictionary<KeyType, ViewModelType>)dictionary;
ViewModelType vm;
if (!viewModels.TryGetValue(key, out vm))
{
vm = new ViewModelType();
viewModels.Add(key, vm);
vm.Initialize(this);
}
return vm;
}
这意味着这两个调用将返回不同的实例:
// Get VM for user.UserId="john";
var userVM1 = viewModelFactory.GetViewModelByKey<UserViewModel, string>("john");
// Get VM for user.UserId="suzie";
var userVM2 = viewModelFactory.GetViewModelByKey<UserViewModel, string>("suzie");
但是这些将返回相同的实例:
// Get the same VM for user.UserId="bob";
var userVM1 = viewModelFactory.GetViewModelByKey<UserViewModel, string>("bob");
var userVM2 = viewModelFactory.GetViewModelByKey<UserViewModel, string>("bob");
这样做的能力解决了很多数据绑定和同步问题,所以我不会轻易放弃这种模式。
但如果可能的话,我希望迁移到标准 IoC 容器,因为大概它们具有更多功能,不需要特定类型,并且肯定更加标准化。但是在阅读它们时,我没有发现任何明显的迹象表明它们支持我的第二种方法。换句话说,它们都支持标准的两种生活方式(单例和瞬态),但我想要一些不同的东西:每个对象身份的单例。标准 IoC 容器是否支持这一点?如何?哪些?
抱歉,这是一个基本问题。
【问题讨论】:
标签: c# mvvm ioc-container