2015-02-06 77 views
1

我正在忙於編寫一個基本上使用託管服務的文件服務器/客戶端工具來向服務器發送數據和從服務器接收數據。由於這個解決方案將被許多不同的人使用,所以不建議讓他們去編輯App.Config文件來進行設置。我想要做的是在運行時改變它,以便用戶可以完全控制要使用的設置。所以,這是我的app.config文件:運行時更改ServiceHost EndPoint地址C#

<system.serviceModel> 
     <services> 
      <service name="FI.ProBooks.FileSystem.FileRepositoryService"> 
       <endpoint name="" binding="netTcpBinding" 
        address="net.tcp://localhost:5000" 
        contract="FI.ProBooks.FileSystem.IFileRepositoryService" 
        bindingConfiguration="customTcpBinding" /> 
      </service> 
     </services> 
     <bindings> 
      <netTcpBinding> 
       <binding name="customTcpBinding" transferMode="Streamed" maxReceivedMessageSize="20480000" /> 
      </netTcpBinding> 
     </bindings> 
    </system.serviceModel> 

我想要做的是改變只有地址(在本例中的net.tcp://本地主機:5000)在執行應用程序。因此,我必須能夠讀取當前值並將其顯示給用戶,然後接受輸入並將其保存回該字段。

回答

0

您可以創建提供配置名稱和端點的服務實例。所以你可以使用;

EndpointAddress endpoint = new EndpointAddress(serviceUri); 
var client= new MyServiceClient(endpointConfigurationName,endpoint) 

msdn文章。

+0

的問題是關於ServiceHost的,而不是客戶端 – 2017-09-06 12:46:18

0

以下測試可能對您有所幫助。基本上這些步驟是

  • 實例化一個從.config文件讀取配置的主機實例;
  • 使用與舊版本相同的配置創建一個新實例EndpointAddress,但更改uri並將其分配給您的ServiceEndpointAddress屬性。

    [TestMethod] 
    public void ChangeEndpointAddressAtRuntime() 
    { 
        var host = new ServiceHost(typeof(FileRepositoryService)); 
    
        var serviceEndpoint = host.Description.Endpoints.First(e => e.Contract.ContractType == typeof (IFileRepositoryService)); 
        var oldAddress = serviceEndpoint.Address; 
        Console.WriteLine("Curent Address: {0}", oldAddress.Uri); 
    
        var newAddress = "net.tcp://localhost:5001"; 
        Console.WriteLine("New Address: {0}", newAddress); 
        serviceEndpoint.Address = new EndpointAddress(new Uri(newAddress), oldAddress.Identity, oldAddress.Headers); 
        Task.Factory.StartNew(() => host.Open()); 
    
        var channelFactory = new ChannelFactory<IFileRepositoryService>(new NetTcpBinding("customTcpBinding"), new EndpointAddress(newAddress)); 
        var channel = channelFactory.CreateChannel(); 
    
        channel.Method(); 
    
        (channel as ICommunicationObject).Close(); 
    
    
        channelFactory = new ChannelFactory<IFileRepositoryService>(new NetTcpBinding("customTcpBinding"), oldAddress); 
        channel = channelFactory.CreateChannel(); 
    
        bool failedWithOldAddress = false; 
        try 
        { 
         channel.Method(); 
        } 
        catch (Exception e) 
        { 
         failedWithOldAddress = true; 
        } 
    
        (channel as ICommunicationObject).Close(); 
    
        Assert.IsTrue(failedWithOldAddress); 
    }