动态生成WCF服务端的简单小例子

为了简单明了我只建了一个控制台程序将服务端跟调用的客户端写在了一起

1.建立服务端接口并实现接口

    [ServiceContract]
    interface ITTest
    {
        [OperationContract]
        string Test();
    }

    class TTest : ITTest
    {
        public string Test()
        {
            return "Service : OK";
        }
    }

 

2.动态生成服务端并调用

        static void Main(string[] args)
        {

            //生成服务端

            Uri HttpAddress = new Uri("http://localhost:8001");
            Uri TcpAddress = new Uri("net.tcp://localhost:8002");

            ServiceHost _ServiceHost = new ServiceHost(typeof(TTest), HttpAddress, TcpAddress);
            _ServiceHost.AddServiceEndpoint(typeof(ITTest), new BasicHttpBinding(), "http://localhost:8001");
            _ServiceHost.AddServiceEndpoint(typeof(ITTest), new NetTcpBinding(), "net.tcp://localhost:8002");

            ServiceMetadataBehavior _ServiceMetadataBehavior = new ServiceMetadataBehavior();
            _ServiceMetadataBehavior.HttpGetEnabled = true;
            _ServiceMetadataBehavior.HttpGetUrl = new Uri("http://localhost:8001");
            _ServiceHost.Description.Behaviors.Add(_ServiceMetadataBehavior);

            _ServiceHost.Open();
            Console.WriteLine("Service : Open");
            Console.ReadLine();

            //调用服务端(http,tcp)

            ITTest HttpProxy = ChannelFactory<ITTest>.CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:8001"));
            Console.WriteLine(HttpProxy.Test());

            ITTest TcpProxy = ChannelFactory<ITTest>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8002"));
            Console.WriteLine(TcpProxy.Test());

            Console.ReadLine();

            _ServiceHost.Close();

        }

 

其实上面动态生成的服务端也可以在 配置文件 app.config中实现

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>

    <services>
      <service name="ConsoleApplication1.TTest" behaviorConfiguration="MyServiceTypeBehaviors">
        <host>
          <baseAddresses>
            <add baseAddress=">
          </baseAddresses>
        </host>
      
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <bindings />
    <client />
  </system.serviceModel>
</configuration>

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值