動態生成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="http://localhost:8010"/>
          </baseAddresses>
        </host>
      
      </service>
    </services>

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

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

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章