1.WCF服务自承载
[ServiceContract(Namespace = "www.matriax.com")]
public interface IWCFService
{
[OperationContract]
string Hello(string name);
}
public class WCFService : IWCFService
{
public string Hello(string name)
{
return String.Format("hello {0}", name);
}
}
using (ServiceHost host = new ServiceHost(typeof(WCFService)))
{
//经过这个endpoint的消息,都有IWCFService这个服务进行处理.注意:这个并没有公布元数据终结点
//但是客户端还是可以访问。原因是客户端已经知道服务的结构,不需要从元数据终结点下载服务结构
//通过代码绑定终结点
host.AddServiceEndpoint(typeof(IWCFService), new NetTcpBinding(), "net.tcp://localhost:8081/WCFService");
//参考配置文件
host.Open();
}
服务端使用配置
<system.serviceModel>
<services>
<service name="WCFServices.WCFService" behaviorConfiguration="servicebehavior">
<endpoint address="WCFService" binding="basicHttpBinding" contract="WCFServices.IWCFService"></endpoint>
<!--元数据交换特定绑定方式,以及内建的元数据交换接口-->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
<host>
<baseAddresses >
<add baseAddress=">
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
2.客户端
使用代码创建代理
首先要将服务契约结构公布到客户端
[ServiceContract(Namespace = "
www.matriax.com")]public interface IWCFService
{
[OperationContract]
string Hello(string name);
}
通过通道工厂创建代理
//首先需要了解服务的结构。需要将服务接口告知到client
IWCFService proxy = ChannelFactory<IWCFService>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8080/WCFService"));
另一种直接添加服务引用或使用命令创建客户端