在上文中,介紹了如何安裝和使用Suteki,今天我們通過源碼來看一下Suteki是如何使用Controller 。
在Suteki中,其使用Abstract的方式來定義一個ControllerBase,以此作為所有Controller的 基類,下面是其Controller的類設計圖:
在該基類中定義了一些Controller中常用到的方法,比如為當前視圖添加MetaDescription,Title等 :
[Rescue("Default"), Authenticate, CopyMessageFromTempDataToViewData]
public abstract class ControllerBase : Controller, IProvidesBaseService
{
private IBaseControllerService baseControllerService;
/// <summary>
/// Supplies services and configuration to all controllers
/// </summary>
public IBaseControllerService BaseControllerService
{
get { return baseControllerService; }
set
{
baseControllerService = value;
ViewData["Title"] = "{0}{1} ".With(
baseControllerService.ShopName,
GetControllerName());
ViewData["MetaDescription"] = "\"{0}\"".With (baseControllerService.MetaDescription);
}
}
public ILogger Logger { get; set; }
public virtual string GetControllerName()
{
return " - {0}".With(GetType().Name.Replace("Controller", ""));
}
public virtual void AppendTitle(string text)
{
ViewData ["Title"] = "{0} - {1}".With(ViewData["Title"], text);
}
public virtual void AppendMetaDescription(string text)
{
ViewData ["MetaDescription"] = text;
}
public string Message
{
get { return TempData["message"] as string; }
set { TempData ["message"] = value; }
}
protected override void OnException (ExceptionContext filterContext) {
Response.Clear();
base.OnException (filterContext);
}
}
當然,細心的朋友發現了該抽象類中還包括一個 IBaseControllerService接口實例。
該接口的主要定義了一些網店系統信息,如店鋪名稱,版權 信息,Email信息等,如下:
public interface IBaseControllerService
{
IRepository<Category> CategoryRepository { get; }
string GoogleTrackingCode { get; set; }
string ShopName { get; set; }
string EmailAddress { get; set; }
string SiteUrl { get; }
string MetaDescription { get; set; }
string Copyright { get; set; }
string PhoneNumber { get; set; }
string SiteCss { get; set; }
}
而作為唯一一個實現了該接口的子類“BaseControllerService”定義如下:
public class BaseControllerService : IBaseControllerService
{
public IRepository<Category> CategoryRepository { get; private set; }
public string GoogleTrackingCode { get; set; }
public string MetaDescription { get; set; }
private string shopName;
private string emailAddress;
private string copyright;
private string phoneNumber;
private string siteCss;
..
}