WCF行為控制代碼示例應(yīng)用解讀
WCF開(kāi)發(fā)工具中有很多比較重要的應(yīng)用技術(shù)及供功能特點(diǎn)需要我們熟練應(yīng)用。在這里我們將會(huì)為大家詳細(xì)介紹一下有關(guān)WCF行為控制的相關(guān)內(nèi)容。希望大家可以從這里介紹的內(nèi)容中獲得相關(guān)幫助。#t#
在完成服務(wù)契約設(shè)計(jì)和服務(wù)實(shí)現(xiàn)后,我們可以設(shè)置該服務(wù)的運(yùn)行期行為(Behavior)。這些WCF行為控制包括 Service Behaviors、Endpoint Behaviors、Contract Behaviors、Operation Behaviors。
有關(guān)所有行為的說(shuō)明,可以查看 ms-help://MS.MSSDK.1033/MS.NETFX30SDK.1033/WCF_con/html/5c5450ea-6af1-4b75-a267-613d0ac54707.htm。
以下就常用的行為使用,做些演示。
ServiceBehaviorAttribute & OperationBehaviorAttribute
這是兩個(gè)最常用的WCF行為控制特性,可用于控制:
服務(wù)對(duì)象生命周期。
并發(fā)管理。
異步通訊。
配置文件參數(shù)。
事務(wù)。
元數(shù)據(jù)轉(zhuǎn)換。
會(huì)話(Session)周期。
等等...
- [ServiceContract]
 - public interface ICalculate
 - {
 - [OperationContract]
 - int Add(int a, int b);
 - }
 - [ServiceBehavior(InstanceContextModeInstanceContextMode=
 
InstanceContextMode.PerCall)]- public class CalculateService : ICalculate
 - {
 - public int Add(int a, int b)
 - {
 - Console.WriteLine(this.GetHashCode());
 - return a + b;
 - }
 - }
 - public class WcfTest
 - {
 - public static void Test()
 - {
 - AppDomain.CreateDomain("Server").DoCallBack(delegate
 - {
 - ServiceHost host = new ServiceHost(typeof(CalculateService));
 - host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(),
 
"http://localhost:8080/calc");- host.Open();
 - });
 - ChannelFactory<ICalculate> factory = new ChannelFactory
 
<ICalculate>(new WSHttpBinding(),- "http://localhost:8080/calc");
 - ICalculate o = factory.CreateChannel();
 - Console.WriteLine(o.Add(1, 2));
 - Console.WriteLine(o.Add(1, 2));
 - factory.Close();
 - }
 - }
 
輸出:
- 30136159
 - 3
 - 41153804
 - 3
 - ServiceMetadataBehavior
 
用于開(kāi)啟元數(shù)據(jù)獲取功能。只有使用該WCF行為控制,客戶端才能通過(guò) Svcutil.exe 或其他工具獲取服務(wù)信息,進(jìn)而生成客戶端代理文件。
- ServiceHost host = new ServiceHost(typeof(CalculateService));
 - host.AddServiceEndpoint(typeof(ICalculate),
 
new BasicHttpBinding(), "http://localhost:8080/calc");- ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
 - behavior.HttpGetEnabled = true;
 - behavior.HttpGetUrl = new Uri("http://localhost:8080/calc");
 - host.Description.Behaviors.Add(behavior);
 - host.Open();
 - ServiceDebugBehavior
 
開(kāi)啟調(diào)試功能,如將服務(wù)器端的異常信息直接傳送給客戶端。
- ServiceHost host = new ServiceHost(typeof(CalculateService));
 - host.AddServiceEndpoint(typeof(ICalculate),
 
new WSHttpBinding(), "http://localhost:8080/calc");- host.Description.Behaviors.Find<ServiceDebugBehavior>()
 
.IncludeExceptionDetailInFaults = true;- host.Open();
 
以上就是對(duì)WCF行為控制的相關(guān)介紹。















 
 
 
 
 
 
 