在我的MVC應用程序中,我使用的是Rob Conery在MVC店面視頻系列中展示的架構,它對我來說就像魅力一樣。
庫=>服務+過濾器=>控制器=>查看
我試圖模仿要達到什麼和管理待辦事項這樣
EDIT1:在庫中改變的IList IQueryable的到和過濾器
庫
public interface IRepository
{
IQueryable<Vote> GetVotes();
IQueryable<Story> GetStories();
}
服務爲得到你想要的
public class Service : IService
{
private IRepository _repository;
public Service(IRepository repository)
{
_repository = repository;
if (_repository == null) throw new InvalidOperationException("Repository cannot be null");
}
public IList<Vote> GetUserVotes(int userID)
{
return _repository.GetVotes().WithUserID(userID).ToList();
}
public IList<Story> GetNotVotedStories(IList<Vote> votes)
{
return _repository.GetStories().WithoutVotes(votes).ToList();
}
}
過濾器來過濾你的故事和用戶投票(這些基本上是擴展方法)。不是最好的實施擺在那裏,但你以後可以改寫
public static class Filters
{
public static IQueryable<Vote> WithUserID(this IQueryable <Vote> qry, int userID)
{
return from c in qry
where c.UserID == userID
select c;
}
public static IQueryable<Story> WithoutVotes(this IQueryable <Story> qry, IList <Vote> votes)
{
return from c in qry
where votes.Where(x => x.StoryID == c.StoryID).ToList().Count > 0
select c;
}
}
然後你就可以在控制器通過當前用戶名,而不是在DAL或視圖像你不得不這樣做之前
public class HomeController : Controller
{
private readonly IRepository _repository;
private readonly IService _service;
public HomeController()
{
_repository = new Repository();
_service = new Service.Service(_repository);
}
public ActionResult Index()
{
var userVotes = _service.GetUserVotes(CurrentUserID);
var unvotedStories = _service.GetNotVotedStories(userVotes);
return View(unvotedStories);
}
}
這可以讓你以避免添加用戶相關UserVotedOn屬性到您的故事模型
那麼,當我說DAL技術上是一個BLL。它包裝了datacontext。當我說ViewData我的意思是我有ViewData類,我傳遞到強類型的意見。感謝您的輸入,我會把它浸入其中。 – 2009-02-09 18:41:01
我自己一直在試圖想出「完美」的MVC架構。經過幾個月的試驗後,我可以說完美的架構和理想的關注分離是不可能的(誰會懷疑)。你只需要認同你自己並做出一些妥協。 – User 2009-02-09 18:49:26