Dot-Net

WCF 配置 - 將其從 app.config 中拆分出來

  • July 2, 2014

我有一個特定要求,將所有客戶端 WCF 配置 (<system.serviceModel>) 從主 app.config 文件中刪除,並放入單獨的 XML 文件中。我希望看到的行為類似於使用 File="" 指令的 appSettings 部分中可用的行為。事實上,理想情況下,我希望能夠為每個使用的服務指定一個單獨的文件……

我知道我可以建構一個自定義 ChannelBuilder 工廠,從 XML 文件(或一系列文件)讀取配置數據,但我更希望客戶端“自動發現”配置數據。

一些基本的Google搜尋似乎表明這是不可能的,但我想從 SO 那裡得到視圖——這裡有人知道我找不到的東西嗎?:)

編輯 ::

Tim Scott 和 davogones 都提出了一個可能的建議,但它依賴於將 system.serviceModel 部分的組件部分拆分為單獨的文件。雖然這不是我想要的(我想離散地定義每個服務及其關聯元素,每個服務一個文件),但它一個選項。我會調查並讓你知道我的想法。

您可以使用 configSource 分離出您的 WCF 配置。這裡的說明:

<http://weblogs.asp.net/cibrax/archive/2007/07/24/configsource-attribute-on-system-servicemodel-section.aspx>

另一種選擇是以程式方式配置 WCF 服務。

using System;
using System.Configuration;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Configuration;

namespace ConsoleHost
{
   public class CustomServiceHost : ServiceHost
   {
       public CustomServiceHost(string customConfigPath, Type serviceType, 
           params Uri[] baseAddresses)
       {
           CustomConfigPath = customConfigPath;
           var collection = new UriSchemeKeyedCollection(baseAddresses);
           InitializeDescription(serviceType, collection);
       }

       public string CustomConfigPath { get; private set; }

       protected override void ApplyConfiguration()
       {
           if (string.IsNullOrEmpty(CustomConfigPath) ||
               !File.Exists(CustomConfigPath))
           {
               base.ApplyConfiguration();
           }
           else
           {
               LoadConfigFromCustomLocation(CustomConfigPath);
           }
       }

       void LoadConfigFromCustomLocation(string configFilename)
       {
           var filemap = new ExeConfigurationFileMap
           {
               ExeConfigFilename = configFilename
           };
           Configuration config = ConfigurationManager.
               OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);

           var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);

           bool loaded = false;
           foreach (ServiceElement se in serviceModel.Services.Services)
           {
               if (se.Name == Description.ConfigurationName)
               {
                   LoadConfigurationSection(se);
                   loaded = true;
                   break;
               }
           }

           if (!loaded)
               throw new ArgumentException("ServiceElement doesn't exist");
       }
   }
}

在這個類之後就像你通常使用它來初始化服務主機一樣使用它

myServiceHost = new CustomServiceHost(ConfigFileName, typeof(QueryTree));

myServiceHost.Open();

引用自:https://stackoverflow.com/questions/482835