编程实现WCF服务
首先當然是編寫契約啦,為了實現契約代碼的復用,這里單獨將契約寫在一個類庫里面Wcf.Contract
1 using System; 2 using System.ServiceModel; 3 4 namespace Wcf.Contract 5 { 6 [ServiceContract(Name="operation",Namespace="urlns://little.org")] 7 public interface IOperation 8 { 9 Guid InstanceId{ get; } 10 [OperationContract] 11 int Add(int a,int b); 12 [OperationContract] 13 int Sub(int a,int b); 14 [OperationContract] 15 int Muti(int a,int b); 16 [OperationContract] 17 int Devide(int a,int b); 18 } 19 }然后就是服務實現啦,將服務實現單獨寫在一個類庫里面 新建一個類庫項目Wcf.Service,并添加Wcf.Contract 引用
using System; using Wcf.Contract;namespace Wcf.Service {public class Operation:IOperation{public Guid InstanceId{get{return Guid.NewGuid();}}public int Add(int a,int b){return a + b;}public int Sub(int a,int b){return a - b;}public int Muti(int a,int b){return a * b;}public int Devide(int a,int b){return a / b;}} }然后就是服務的承載了,我們新建一個Wcf.Host 的控制臺項目,在控制臺中承載服務
1 using System; 2 using System.ServiceModel; 3 using Wcf.Service; 4 5 namespace Wcf.Host 6 { 7 class MainClass 8 { 9 public static void Main (string[] args) 10 { 11 Uri[] baseAddresses = new Uri[] { 12 new Uri ("http://localhost:8081/operation", UriKind.Absolute) 13 }; 14 ServiceHost host = new ServiceHost (typeof(Wcf.Service.Operation), baseAddresses); 15 16 host.AddServiceEndpoint ("Wcf.Contract.IOperation", new BasicHttpBinding (), ""); 17 host.Opened += OnServiceHostOpened; 18 try 19 { 20 host.Open(); 21 } 22 catch(Exception ex) { 23 //Console.BackgroundColor = ConsoleColor.Red; 24 Console.WriteLine (ex.Message); 25 //Console.ResetColor (); 26 } 27 Console.WriteLine ("press any key to exit..."); 28 Console.ReadKey (); 29 30 31 } 32 33 public static void OnServiceHostOpened(object sender,EventArgs e) 34 { 35 Console.WriteLine ("ServiceHost has opened."); 36 } 37 } 38 }這樣就簡單實現了一個Wcf服務,沒有使用配置文件
轉載于:https://www.cnblogs.com/yayaxxww/p/4282749.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: Unity编辑器扩展Texture显示选
- 下一篇: 数据结构二叉树的所有基本功能实现。(C+