在“nekno”的回复中(9 月 30 日 22:19 回答),ViewModel 有两种选择,它们返回一个 'IEnumerable' 或一个 'IEnumerable'。
这两种替代方法都使用存储库,但没有实际创建它,所以我想稍微扩展一下代码示例,并选择第二种替代方法,即属性类型为 'IEnumerable' 的类:
using Microsoft.Practices.ServiceLocation; // ServiceLocator , http://commonservicelocator.codeplex.com/
using MyOwnRepositoryNameSpace; // IRepository
public class EditViewModel
{
public int? FooType { get; set; }
public IEnumerable<int?> FooTypes
{
get
{
return Repository.GetFooTypes();
}
}
private IRepository Repository
{
get
{
return ServiceLocator.Current.GetInstance<IRepository>();
}
}
}
上述带有“依赖查找”的代码现在使用对第三方库的依赖,在本例中是公共服务定位器库。
我的问题是如何将上面的代码替换为“依赖注入”?
ViewModel 本身确实很容易实现,就像这样:
using MyOwnRepositoryNameSpace; // IRepository
public class EditViewModel
{
private readonly IRepository _repository;
public EditViewModel(IRepository repository)
{
_repository = repository;
}
public int? FooType { get; set; }
public IEnumerable<int?> FooTypes
{
get
{
return _repository.GetFooTypes();
}
}
}
问题是如何让 ViewModel 注入一个实现,当 ASP.NET MVC 框架将实例化“EditViewModel”并将其作为参数发送到诸如 tihs 方法签名之类的 Action 方法中时:
public ActionResult Edit(int id, EditViewModel model) {
// How do we make the framework instantiate the above 'EditViewModel' with an implementation of 'IRepository' when the Action method is invoked ???
据我所知,官方 MVC 教程似乎没有提供任何好的解决方案。
在以下页面的“处理编辑”部分(方法 'public ActionResult Edit(...)' )中,他们以与您正在阅读的这个 stackoverflow 问题的海报类似的方式复制选项的创建。
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-5
http://mvcmusicstore.codeplex.com/SourceControl/changeset/view/d9f25c5263ed#MvcMusicStore%2fControllers%2fStoreManagerController.cs
如果有关于如何使用数据检索器(例如存储库)使框架注入视图模型的解决方案,那么我相信它可能是使用“IModelBinderProvider”或“IModelBinder”的一些实现,但我已经尝试过了这些都没有真正的成功......
那么,任何人都可以提供一个完整的工作示例的链接,该示例使用 ASP.NET MVC 3 代码可以将数据检索器注入到框架实例化的视图模型的构造函数中,并将作为参数发送到操作方法中?
2012-01-01 更新:
对于那些对有关 ViewModel 实例的构造函数注入的特定问题的解决方案感兴趣的人,当框架实例化它并将其作为参数发送到 MVC 操作方法参数时,我创建了一个具有更具体主题的新问题,因此希望更有可能有解决方案的人会找到它并发布一个好的答案:
Constructor injection of a View Model instance used as an Action method parameter