【发布时间】:2015-06-11 16:35:50
【问题描述】:
目前我正在使用 DI 和服务定位器模式来获取服务实例。 (请注意,Service 只是我使用的通用术语,只不过是调用 EF 存储库并执行数据操作的 C# 类。它不是 WCF 服务)
可以在 ViewModel 中有 Service 实例吗?如果是,传递服务实例的正确方法是什么?
1>控制器是否应该将服务实例传递给 ViewModel。在这种情况下,当控制器被处理时,服务会被正确处理
2>或者 ViewModel 应该使用 DI 和服务定位器获取服务实例。在这种情况下,服务将如何处理?
基础控制器
public class BaseController:Controller
{
private MyDomainService _myDomainServiceInstance = null;
protected MyDomainService MyDomainServiceInstance
{
get
{
if (_myDomainServiceInstance == null)
{
_myDomainServiceInstance = DefaultServiceLocator.Instance.GetInstance<MyDomainService>();
}
return _myDomainServiceInstance;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_myDomainServiceInstance != null)
{
_myDomainServiceInstance.Dispose();
}
}
}
控制器
public class MyController:BaseController
{
public ActionResult DoSomething()
{
var model = new SummaryVM(MyDomainServiceInstance);
}
}
视图模型
public class SummaryVM
{
MyDomainService _myDomainService = null;
public SummaryVM(MyDomainService myDomainService)
{
//Approache 1: Controller is passing the service instance
_myDomainService = myDomainService;
}
public SummaryVM()
{
//Aprooche 2: Use DI & Service locator pattern to get the instance
_myDomainService = DefaultServiceLocator.Instance.GetInstance<MyDomainService>();
}
public int[] SelectedClients { get; set; }
public string[] SelectedStates { get; set; }
public IEnumerable<Clients> PreSelectedClients
{
get
{
if (SelectedClients == null || !SelectedClients.Any())
{
return new List<AutoCompletePreSelectedVM>();
}
return _myDomainService.GetClients(SelectedClients);
}
}
}
【问题讨论】:
标签: asp.net-mvc viewmodel domainservices