關鍵要點
許多REST服務中都包含重複的模式;
如果能自動產生這些模式相關的代碼就可以節省很多時間;
Visual Studio的T4和EnvDTE具有強大的產生代碼功能,不需要更多工具輔助;
也可以用相似技術產生對WCF和資料庫的調用;
在Visual Studio中,T4文本模板用文字和控制邏輯的混合物來產生文字檔。控制邏輯是用Visual C#或者Visual Basic語言寫成的代碼塊。在Visual Studio 2015 Update 2及以後版本中,也可以在T4模板指令中使用C# V6.0的新功能。產生的檔案可以是任意類型的文本,包括網頁、資源檔、甚至是任何程式設計語言的原始碼。在微軟公司內部T4應用得很廣泛。他們用它來產生MVC視圖、控制器、EntityFramework上下文等等。
對於那些想要根據已有的模式或模型產生代碼,或者寫最少的重複性代碼的開發人員來說,都可以嘗試使用T4。我們可以用T4產生代碼來簡單地封裝對商務邏輯或者任何其它服務的調用,也可以增加日誌功能、實現緩衝機制、基於某些模型來建立請求/響應類、甚至實現商務邏輯……等等。
REST服務通常都被簡單地作為商務邏輯的封裝器,因此我們就可以使用T4來自動地為我們的介面和模型產生REST/WCF或者任意其它服務。這樣就可以把開發人員解放出來,讓他們有更多的時間去專心處理用C#和SQL實現的商務邏輯。
用例
假如我們準備開發一個簡單的服務,來處理GET、批量GET、Insert和Update方法。產品實體包含下面這些屬性:
public partial class Product
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public int ProductGroupId { get; set; }
public decimal? ListPrice { get; set; }
public decimal? Size { get; set; }
public decimal? Weight { get; set; }
public ProductGroup ProductGroup { get; set; }
}
需求要求可以通過產品的名字、數量、價格範圍等方面來尋找過濾產品。當插入一條產品記錄時,我們會把除了Id和數量之外的所有屬性都寫上。這些全是自動產生的,所以我們也不能更改它們。為了提高效能,使用者也可以指定是否需要添加ProductGroup對象。如果不需要聯結操作或者隔離ProductGroup的查詢,就可以不添加。
為了協助大家理解,我在這裡畫了一張圖來展示我在這篇文章中要用到的架構:
批量GET方法
如上文所述,我們需要通過產品的名字、數量或價格範圍等做過濾,這通常叫做“過濾類”或者“查詢對象”,如果全用手工實現的話就太枯燥了。
但通過T4、EnvDTE和模型的屬性,我們也可以自動建立新的過濾類。比如,我們可以設定模型的如下屬性:
public partial class Product
{
...
[Filter(FilterEnum.GreatherThanOrEqual)]
public string Name { get; set; }
[Filter(FilterEnum.Equal | FilterEnum.List)]
public string Number { get; set; }
[Filter(FilterEnum.GreatherThanOrEqual | FilterEnum.LowerThanOrEqual)]
public decimal? ListPrice { get; set; }
...
}
使用T4可以自動產生包含這些屬性的類:
public partial class ProductSearchObject : BaseSearchObject<ProductAdditionalSearchRequestData>
{
//some code ommited (private members and attributes)
public virtual System.String NameGTE { get; set; }
public virtual System.String Number { get; set; }
public virtual IList<String> NumberList { get {return mNumberList;} set { mNumberList = value; }}
public virtual System.Nullable<System.Decimal> ListPriceGTE { get; set; }
public virtual System.Nullable<System.Decimal> ListPriceLTE { get; set; }
}
要是使用EntityFramework的話,我們就可以輕鬆產生業務處理邏輯,就是包含基於這個查詢對象和模型的LINQ查詢。要這樣做,首先要定義介面和準備使用的屬性。比如:
[DefaultServiceBehaviour(DefaultImplementationEnum.EntityFramework, "products")]
public interface IProductService : ICRUDService<Product, ProductSearchObject, ProductAdditionalSearchRequestData, ProductInsertRequest, ProductUpdateRequest>
{
}
做完這一步,T4就知道了預設的實現應該是怎樣,然後就可以產生基於查詢對象的檢索邏輯了:
protected override void AddFilterFromGeneratedCode(ProductSearchObject search, ref System.Linq.IQueryable<Product> query)
{
//call to partial method
base.AddFilterFromGeneratedCode(search, ref query);
if(!string.IsNullOrWhiteSpace(search.NameGTE))
{
query = query.Where(x => x.Name.StartsWith(search.NameGTE));
}
if(!string.IsNullOrWhiteSpace(search.Number))
{
query = query.Where(x => x.Number == search.Number);
}
if(search.NumberList != null && search.NumberList.Count > 0)
{
query = query.Where(x => search.NumberList.Contains(x.Number));
}
if(search.ListPriceGTE.HasValue)
{
query = query.Where(x => x.ListPrice >= search.ListPriceGTE);
}
if(search.ListPriceLTE.HasValue)
{
query = query.Where(x => x.ListPrice <= search.ListPriceLTE);
}
}
可以把我們的預設實現註冊到IoC架構中:
public partial class ServicesRegistration : IServicesRegistration
{
public int Priority {get; set; }
public ServicesRegistration()
{
Priority = 0; //This is root, If you want to override this. Add new class with higher priority
}
public void Register(UnityContainer container)
{ container.RegisterType<IProductService,ProductService>(new HierarchicalLifetimeManager());
}
}
如果用這種方法構建,我們還可以非常容易地用另一個更高優先順序的類來重載這種註冊過程,以此來替換這種實現。
在產生REST API時,T4還會根據介面中的屬性資訊來決定要為哪些屬性產生擷取函數。比如,在IProductService介面中我們可以為相應屬性這樣添加函數:
[DefaultMethodBehaviour(BehaviourEnum.Get)]
PagedResult<TEntity> GetPage(TSearchObject search);
既然我們知道了有哪些函數可以用於擷取資料,我們就可以為REST服務產生代碼了:
[RoutePrefix("products")]
public partial class productsController : System.Web.Http.ApiController
{
[Dependency]
public IProductService Service { get; set; }
[Route("")]
[ResponseType(typeof(PagedResult<Product>))]
[HttpGet]
public System.Web.Http.IHttpActionResult GetPage ([FromUri] ProductSearchObject search)
{
//call to partial method
var result = Service.GetPage(search);
return Ok(result);
}
}
如前文所述,我們希望用戶端可以按需要請求ProductGroup這種附加資訊,要具備這個功能,只要給ProductGroup屬性加上[LazyLoading]指令就可以了。
public partial class Product
{
//ommited code
[LazyLoading]
public ProductGroup ProductGroup { get; set; }
}
加上[LazyLoading]指令之後,T4就會給新建立的類中加上IsProductGroupLoadingEnabled變數。
public partial class ProductAdditionalSearchRequestData : A.Core.Model.BaseAdditionalSearchRequestData
{
public virtual bool? IsProductGroupLoadingEnabled { get; set; }
}
在底層使用EntityFramework會產生如下代碼:
protected override void AddInclude(ProductSearchObject search, ref System.Linq.IQueryable<Product> query)
{
if(search.AdditionalData.IsProductGroupLoadingEnabled.HasValue && search.AdditionalData.IsProductGroupLoadingEnabled == true)
{ search.AdditionalData.IncludeList.Add("ProductGroup");
}
base.AddInclude(search, ref query); //calls EF .Include method
}
Insert方法
插入對象的屬性列表常常與完整的模型不同。比如,那些自動產生的主鍵就不應該由用戶端傳入,因為它們應該被忽略掉。這個例子當然很明顯,但還是有些欄位會非常容易出問題。
比如ProductGroup屬性,如果我們把它也包含到插入對象之中,那大家就會有誤解,以為用戶端應該用這個函數調用去建立或者更新一個ProductGroup。所以最好是提供一個明確的插入對象,而不要重用完整模型。
為了避免用重複性地手工勞動來建立這些代碼,我們仍然可以用指令來要求它為我們產生需要的屬性,比如:
[Entity]
public partial class Product
{
[Key]
public int Id { get; set; }
[Filter(FilterEnum.GreatherThanOrEqual)]
[RequestField("Insert")]
public string Name { get; set; }
[Filter(FilterEnum.Equal | FilterEnum.List)]
public string Number { get; set; }
[RequestField("Insert")]
public int ProductGroupId { get; set; }
[RequestField("Insert")]
[Filter(FilterEnum.GreatherThanOrEqual | FilterEnum.LowerThanOrEqual)]
public decimal? ListPrice { get; set; }
[RequestField("Insert")]
public decimal? Size { get; set; }
[RequestField("Insert")]
public decimal? Weight { get; set; }
[LazyLoading]
public ProductGroup ProductGroup { get; set; }
}
上面的資訊可以產生下面的代碼,即ProductInsertRequest類:
public partial class ProductInsertRequest
{
public System.String Name { get; set; }
public System.Int32 ProductGroupId { get; set; }
public System.Nullable<System.Decimal> ListPrice { get; set; }
public System.Nullable<System.Decimal> Size { get; set; }
public System.Nullable<System.Decimal> Weight { get; set; }
}
和以前一樣,我們要修改一下介面,這樣T4就知道哪些函數是負責處理插入請求的。我們可以為合適的函數加上屬性,比如:
[DefaultMethodBehaviour(BehaviourEnum.Insert)]
TEntity Insert(TInsert request, bool saveChanges = true);
有了這些模型和介面的資訊,T4就可以產生我們想要的REST API代碼了:
[Route("")]
[ResponseType(typeof(Product))]
[HttpPost]
public HttpResponseMessage Insert([FromBody] ProductInsertRequest request)
{
var result = Service.Insert(request);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, result);
return response;
}
Update方法
原理也和插入函數一樣。在這裡我們要為元組的屬性加上[RequestField("Update")]指令,這樣就可以為ProductUpdateRequest產生合適的屬性。然後再為相應的介面加上指令來讓T4知道哪個函數是要處理Update的。
加上這些指令後,T4就可以為REST服務產生更新資料的函數了:
[Route("{id}")]
[ResponseType(typeof(A.Core.Model.Product))]
[HttpPut]
public HttpResponseMessage Update([FromUri] Int32 id, [FromBody]ProductUpdateRequest request)
{
//can return "Not Found" if Update throws NotFoundException
var result = Service.Update(id,request);
var response = Request.CreateResponse<Product>(HttpStatusCode.OK, result);
return response;
}
結論
從文中可以看出,我們可以用T4來產生代碼,協助我們節省很多寫重複性代碼的時間。產生的程式碼易讀性也很好,和自己寫的一樣。用相同的辦法,我們也可以產生代碼來在服務等級緩衝結果和增加日誌功能。
這種技術的另一種用途是同時產生REST和WCF服務代碼,當你的用戶端既要支援瀏覽器也要支援C#時這就很有用。
在我的工作經曆中,我曾經用T4和EnvDTE來為公司的項目產生完整的CRUD REST服務代碼,包括資料庫調用和單元測試等。幾分鐘就搞定了,而不是幾小時。