LitwareHR使用WCF正確實(shí)現(xiàn)方法詳解
眾所周知,WCF開發(fā)插件是一個(gè)功能強(qiáng)大,應(yīng)用范圍比較廣泛的.NET Framework 3.5重要組成部件。在這里我們將會為大家詳細(xì)介紹一下LitwareHR使用WCF的正確實(shí)現(xiàn)方法,希望能給大家?guī)硪恍椭?t#
LitwareHR是微軟的一個(gè)開源代碼,主要目的是為了解釋如何使用WCF等技術(shù)開發(fā)一個(gè)實(shí)現(xiàn)微軟的SaaS,如下:
To be the embodiment of the architectural guidance described in our whitepapers
To demonstrate how the Microsoft platform is used in the creation of SaaS solutions
關(guān)于SaaS這里不再描述,LitwareHR在架構(gòu)上也有很多可以參考的地方,具體可以去看他的文檔和代碼
這里關(guān)注一下LitwareHR使用WCF的正確實(shí)現(xiàn)方法,尤其是在使用WCF的時(shí)候是如何劃分層次結(jié)構(gòu)的.
其實(shí),如果我們關(guān)注微軟的軟件工廠,就會發(fā)現(xiàn)在微軟的Service Factory里面,也是采用了類似的層次結(jié)構(gòu)
總的來說,在LitwareHR里面,對于某一個(gè)功能來說,從門戶端(下面稱之為客戶端)到中間層(下面稱之為服務(wù)端)一共會涉及這么幾個(gè)模塊:
Gateway,Host,Service,Contract,BusinessLogic,這里,從其中的一個(gè)具體業(yè)務(wù),GetMainMenuList作為例子.
其中:
Gateway,是一個(gè)典型的Service Gateway的Enterprise Pattern的應(yīng)用,包裝了對服務(wù)的應(yīng)用,這個(gè)是跑在客戶端的,包裝在一個(gè)gateways的DLL中
比如:
PresentationGateway.cs中
- static public MainMenuItem[] GetMainMenuList()
- {
- using (SecureChannel channel = new SecureChannel())
- {
- return channel.GetMainMenuList();
- }
- }
- private class SecureChannel : ClientBase<IPresentationSC>, IPresentationSC
- {
- public MainMenuItem[] GetMainMenuList()
- {
- return base.Channel.GetMainMenuList();
- }
- }
上面的IPresentationSC以及MainMenuItem都是Contract里面描述的接口以及對象
Contract,是接口,包裝在獨(dú)立的DLL中,客戶端和服務(wù)端都會用到
比如:
MainMenuItem.cs中描述了傳輸?shù)臄?shù)據(jù)對象
- [DataContract, Serializable]
- public class MainMenuItem
- {
- private object _id;
- [DataMember]
- public object Id
- {
- get { return _id; }
- set { _id = value; }
- }
- ….
- }
IPresentationSC.cs中描述了服務(wù)接口,
- [ServiceContract]
- public interface IPresentationSC
- {
- …
- [OperationContract]
- MainMenuItem[] GetMainMenuList();
- }
Host:很簡單,就是宿主程序,這里是宿主的IIS里面的,所以就是一個(gè)web site,自然是服務(wù)端的
比如
在其中的PresentationService.svc中(就這么一句話,這也是適用IIS作為WCF宿主的好處之一)
- <% @ServiceHost Language=C# Debug="true" Service=
"Shp.Runtime.Services.PresentationService" %>
Service:這是host文件里面指定的service類,自然是服務(wù)端的
比如:
在PresentationService.cs中
- public class PresentationService : IPresentationUC, IPresentationSC
- {
- ...
- public MainMenuItem[] GetMainMenuList()
- {
- Thread.CurrentThread.CurrentCulture = CultureInfo.InstalledUICulture;
- Guid tenantId = Context.TenantId;
- if (tenantId == Guid.Empty)
- throw new System.Security.SecurityException();
- return PresentationLogic.GetMainMenuList(tenantId);
- }
- }
這里調(diào)用到了PresentationLogic類, LitwareHR中,這個(gè)東西和Service放在一個(gè)DLL中,但是不同的cs
這就是前面提到的BusinessLogic,比如PresentationLogic.cs,實(shí)現(xiàn)具體的業(yè)務(wù)邏輯
當(dāng)然,如果足夠復(fù)雜的話,其實(shí)底層還可以實(shí)現(xiàn)業(yè)務(wù)實(shí)體以及業(yè)務(wù)實(shí)體轉(zhuǎn)換的模塊,這些可以在service factory里面看到微軟的推薦做法,這里不說了
還有一個(gè)沒有提到的,就是客戶端和服務(wù)端的配置文件里面都會有相應(yīng)的內(nèi)容,這里不贅述了
總結(jié):可以看出,LitwareHR使用WCF的時(shí)候,其程序?qū)哟谓Y(jié)構(gòu)相比較web service會多一些,更為靈活,但是實(shí)際上,對于web service,我們也可以抽象出這么多層次,只不過比較別扭而已(比如在web service里面,實(shí)際上contract的概念并不是很強(qiáng))