1

現在、リポジトリ、Unit-Of-Workパターン、Service Layer、ViewModelsを使用してAsp.NetMVCに取り組んでいます。

このプロジェクトでは、すべてのビューがViewModelクラスにリンクされており、コントローラーはシン1であるため、ビジネスレイヤーはサービスレイヤーに存在します。

コントローラで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
            }
        }
4

1 に答える 1

5

コントローラーは、いわば制御する必要のあるコンポーネントです。ViewModelは単なるデータコンテナであり、それ以上のものではありません。

単一責任の原則を忘れないでください。ロジックの配布を開始すると、すべての可動部分を覚えて理解することがますます難しくなります。

于 2012-10-08T06:10:18.107 に答える