目前我正在使用:存储库、工作单元模式、服务层和视图模型来开发 Asp.Net MVC。
在这个项目中,每个视图都链接到一个 ViewModel 类,控制器是瘦的,因此业务层位于服务层上。
我在控制器中创建 ViewModel 类的实例并将其传递给这样的视图
public ActionResult Create()
{
EventCreateViewModel eventViewModel = new EventCreateViewModel();
return View(eventViewModel);
}
在一些 ViewModel 中我用来调用服务层。
系统可以工作,但我想知道在 ViewModel 中添加对服务层的调用是否是个好主意,或者更好的是将此操作留给控制器。
public class EventCreateViewModel
{
public CandidateListViewModel CandidateList = new CandidateListViewModel();
public EventCreateViewModel()
{
DateTimeStart = DateTime.UtcNow; // Add a default value when a Date is not selected
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XXX.Models;
using XXX.Service;
namespace XXX.ViewModels
{
public class CandidateListViewModel
{
// We are using the Service Layer
private ICandidateBL serviceCandidate;
// Property
public IDictionary<string, string> Candidates = new Dictionary<string, string>();
// An utility method that convert a list of Canddates from Enumerable to SortedDictionary
// and save the result to an inner SortedDictionary for store
public void ConvertSave(IEnumerable<Candidate> candidates)
{
Candidates.Add("None", "0"); // Add option for no candidate
foreach (var candidate in candidates)
Candidates.Add(candidate.Nominative, candidate.CandidateId.ToString());
}
#region Costructors
public CandidateListViewModel()
{
serviceCandidate = new CandidateBL();
ConvertSave(serviceCandidate.GetCandidates());
}
// Dependency Injection enabled constructors
public CandidateListViewModel(ICandidateBL serviceCandidate)
{
this.serviceCandidate = serviceCandidate;
}
public CandidateListViewModel(IEnumerable<Candidate> candidates)
{
serviceCandidate = new CandidateBL();
ConvertSave(candidates);
}
#endregion
}
}