【问题标题】:Understanding and Using "Service Layers" - .NET MVC 5理解和使用“服务层”——.NET MVC 5
【发布时间】:2014-09-11 23:22:29
【问题描述】:

我目前正在实习,据我所知,MVC 中的控制器应该只用于流量,并且只能用于流量。我还被告知称为“服务层”的东西,这听起来像是我应该为控制器执行任何数据/业务逻辑的地方。

我一直在四处寻找这方面的示例和教程,但我没有找到任何对我来说足够愚蠢的东西,因为我大约一个月前才学习了 MVC。我想知道是否有人能够解释并向我展示如何将以下ActionResult Index 业务逻辑转移到“服务层”中。

public class LakerLegendsController : Controller
{    
    string pathway1 = HostingEnvironment.MapPath(@"~/App_Data/Announcement1.txt");
    string pathway2 = HostingEnvironment.MapPath(@"~/App_Data/Announcement2.txt");
    string pathway3 = HostingEnvironment.MapPath(@"~/App_Data/Announcement3.txt");
    private MoviesEntities db = new MoviesEntities();

public ActionResult Index()
{
    // Setting some ViewBag texts from announcement files.
    string text1 = System.IO.File.ReadAllText(pathway1);
    ViewBag.TextHTML1 = text1;

    string text2 = System.IO.File.ReadAllText(pathway2);
    ViewBag.TextHTML2 = text2;

    string text3 = System.IO.File.ReadAllText(pathway3);
    ViewBag.TextHTML3 = text3;


    // Following pulls some XML information
    XDocument xmlFile = XDocument.Load(@"http://na.leagueoflegends.com/en/rss.xml");


    var LoLtitles = from service in xmlFile.Descendants("item")
            select (string)service.Element("title");
    var LoLlinks = from service in xmlFile.Descendants("item")
             select (string)service.Element("link");
    var LoLdescriptions = from service in xmlFile.Descendants("item")
             select (string)service.Element("description");
    var LoLDates = from service in xmlFile.Descendants("item")
              select (string)service.Element("pubDate");

    var servicing = LoLdescriptions.ToArray();
    for (int i = 0; i < 4; i++)
    {
        servicing[i] = Regex.Replace(Server.HtmlDecode(servicing[i]), @"<[^>]*>", String.Empty);
    }

    ViewBag.titles = LoLtitles.ToArray();
    ViewBag.links = LoLlinks.ToArray();
    ViewBag.descriptions = servicing;
    ViewBag.dates = LoLDates.ToArray();

    // Pulls the DB Table
    var users = db.Users.Include(u => u.championList).Include(u => u.championList1).Include(u => u.championList2).Include(u => u.eloList).Include(u => u.rankList).Include(u => u.roleList).Include(u => u.roleList1);
    return View(users.ToList());
}
}

这段代码所做的只是返回一个数据库表,以及一些提取 XML 文件并解析其中一些信息的额外逻辑。

我想知道如何将这个特定示例转换为使用服务层(或者我应该用于逻辑的任何东西)。请尽量简化,因为我还是 MVC 的新手。

【问题讨论】:

    标签: asp.net-mvc model-view-controller asp.net-mvc-5 service-layer


    【解决方案1】:

    服务层定义了与客户端层接口相关的一组可用操作,即封装应用程序的业务逻辑。它们只是不同类库(或命名空间)中的一个单独的类,它们独立于 MVC 框架基础结构,可由 ASP.NET Web API 或 WCF 使用。

    我一直在寻找这方面的示例和教程,但我 我没有找到任何让我觉得足够愚蠢的东西

    这是非常知名的音乐商店的一个很好的例子。这可以帮助您通过 DI Injecting a Controller MSDN 完成服务层

    服务层的目的是为了解耦和可维护性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-29
      • 2019-09-18
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      相关资源
      最近更新 更多