菜阿斌以前寫了兩篇很好的文章:為什么要讓我們的“領域模型”裸奔?(上),(下),在我的 架構視角面面觀中也介紹了領域邏輯經常被Web 組件Api、分布組件Api、ORM組件API、ADO API 等污染,上面的幾篇文章講了領域裸奔的重要性、以及常見項目中的領域被污染的問題,關於如何解決該問題, 網上關於這方面的介紹倒很少。本篇將介紹如何讓我們的領域邏輯不被Web組件、分布組件所污染,解決該問題的主角將是NLite.WebAPI 組件,下面就讓它登場吧。
NLite WebApi
NLite web api 是基於NLite.Web和 Ndf的服務分發器引擎,並借助Asp.net 的http原生態無狀態協議的基礎上搭建起來的 ,NLite Web api 完全無侵入性,不繼承任何基類,只需要簡單的配置即可把業務邏輯自動分發成NLite Web Api 服務。
准備工作
- 新建一個空的ASP.NET Web Application項目

2. 通過Nuget 下載NLite.Web 組件:install-package nui (NUI 是NLite.Web 組件在Nuget庫中的標志Id)

3. 添加裸奔的領域邏輯:CalculateService(這里僅僅為了演示,沒有把領域邏輯放到單獨的項目中)
public class CalculateService { public int Add(int a, int b) { return a + b; } public int Sub(int a, int b) { return a - b; } public int Multiply(int a, int b) { return a * b; } public int Divide(int a, int b) { return a / b; } }
配置NLite WebApi
1. 添加Global文件(下面步驟的配置代碼如果沒有特殊說明的話都在Application_Start方法中放着),並導入下面的namespace
using NLite; using NLite.Cfg; using NLite.Domain.Cfg; using NLite.Web;
2. 創建NLite 配置對象
var cfg = new NLite.Cfg.Configuration();
3. 配置NLite的DI 容器-Mini容器
//配置DI容器 cfg.Configure();
4. 配置WebApi的Url 路由映射模版:api/{controller}/{action}/{id},那么CalculateService的Add方法對應的Url為:api/calculate/add
//配置WebAPI 路由服務 cfg.MapRequestRoute(new ServiceRouteOption { Name = "WebApi", Url = "api/{controller}/{action}/{id}", Defaults = new { id = NLite.Web.UrlParameter.Optional } });
5. 異常處理配置
//異常配置 cfg.Add(new ExceptionConfigurationItem(container => { container .Register<NLite.Domain.ExceptionCode>()//注冊異常編碼規則 .Register<NLite.Web.Service.HttpJsonExceptionRender>()//注冊Json格式的異常呈現器 .Register<LogExceptionReander>()//注冊日志格式的異常呈現器 .Register<ServiceDispatcherExceptionResolver>()//注冊服務分發異常解析器 .Register<DomainExceptionResolver>()//注冊領域(業務)異常解析器 .Register<DbExceptionResolver>()//注冊Db異常解析器 .Register<UnknowExceptionResolver>()//注冊未知異常解析器 .Register<ExceptionHandler>();//注冊異常處理器 }));
6. 配置領域邏輯組件(比如Demo的CalculateService)
//配置領域服務 cfg.Add(new DomainComponentConfigurationItem(container => { LifestyleType.Default = LifestyleFlags.Transient; container.Register<CalculateService>(); }));
F5 運行NLite WebApi
1. 在瀏覽器中輸入:http://localhost:9620/api/calculate/add?a=2&b=3,那么NLite WeApi的調用流程:NLite.WebApi->NDF->CalculateService.Add(2,3)

備注: code 是服務器返回的狀態碼,code=1是成功,反之失敗,data 的內容就是服務返回的真正結果
2. 在瀏覽器中輸入:http://localhost:9620/api/calculate/multiply?a=2&b=3,那么NLite WeApi的調用流程:NLite.WebApi->NDF->CalculateService.Multiply(2,3)

總結
通過上面的例子看出,我們的領域邏輯組件CalculateService,非常干凈,沒有被任何Asp.net Web組件污染,也沒有被任何分布框架的Api污染,僅僅需要簡單的領域組件注冊即可自動的發布成WebApi組件。

本篇的NLite WebApi 的配置和Demo例子都是手寫的,其實這篇文章 :給Web Api 再加把柴-讓它更火起來 給大家一個更簡單的方式來使用WebApi。為了更進一步了解WebApi 底層的Ndf服務分發器可以看看這篇文章:松耦合服務調用利器-服務分發器。
