使用SOA來實現兩個數字的相加,不包含驗證,僅供練習使用。
PDF文檔下載地址:http://files.VEVb.com/chenyongblog/SOA_Demo.pdf
源碼下載:http://files.VEVb.com/chenyongblog/WCFTest.7z
1、首先定義一個接口ICalculate
(1)引入System.ServiceModel程序集
(2)公開接口,使用ServiceContract特性定義服務契約(標注interface),OpeattionContract特性標注Method
using System.ServiceModel;namespace CalculateImplement{ [ServiceContract] public interface ICalculate { [OperationContract] double Add(double x, double y); }}
2、接口的實現
namespace CalculateImplement{ public class Calculate : ICalculate { public double Add(double x, double y) { return x + y; } }}
3、Host管理服務
<?xml version="1.0" encoding="utf-8" ?><configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <!--WCF Setting--> <system.serviceModel> <services> <service name="CalculateImplement.Calculate" behaviorConfiguration="serviceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:9001"/> </baseAddresses> </host> <endpoint name="CalculateImplementEndPoint" address="CalculateImplement" binding="basicHttpBinding" contract="CalculateImplement.ICalculate"/> <endpoint name="mex" binding ="mexHttpBinding" contract="IMetadataExchange" address="mex"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="serviceBehavior"> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel></configuration>
using System;using System.ServiceModel;using CalculateImplement;namespace HostService{ class PRogram { static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(Calculate)); try { host.Open(); Console.WriteLine("Service is open......"); Console.ReadLine(); host.Close(); } catch (Exception et) { throw et; } } }}
4、開啟Host,在Client端添加Service,修改命名空間
Client代碼:
using System;namespace Client{ class Program { static void Main(string[] args) { CalculateService.CalculateClient calculate = new CalculateService.CalculateClient(); Console.WriteLine("SOA Demo"); Console.Write("Please enter the first number:"); double num1 = Convert.ToDouble(Console.ReadLine()); Console.Write("Please enter the second number:"); double num2 = Convert.ToDouble(Console.ReadLine()); double result = calculate.Add(num1, num2); Console.WriteLine("Add result:" + result); Console.ReadLine(); } }}
程序運行:
新聞熱點
疑難解答