
·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> SOADemo
使用SOA来实现两个数字的相加,不包含验证,仅供练习使用。
PDF文档下载地址:http://files.cnblogs.com/chenyongblog/SOA_Demo.pdf
源码下载:http://files.cnblogs.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();
}
}
}
程序运行:

