2011-02-18 48 views
5

我有一個使用插件系統的Windows服務。我用下面的代碼的插件基類,以提供每個DLL一個單獨的配置(所以它會從plugin.dll.config讀):App.config之外的WCF ChannelFactory配置?

string dllPath = Assembly.GetCallingAssembly().Location; 
return ConfigurationManager.OpenExeConfiguration(dllPath); 

這些插件需要對WCF服務調用,所以這個問題我運行的是new ChannelFactory<>("endPointName")只在託管應用程序的App.config中查找端點配置。

有沒有辦法簡單地告訴ChannelFactory查看另一個配置文件或以某種方式注入我的Configuration對象?

我能想到的解決方法的唯一方法是從plugin.dll.config中讀取的值中手動創建EndPoint和Binding對象,並將它們傳遞給ChannelFactory<>重載之一。這看起來好像重新創建輪子,並且可能會大量使用行爲和綁定配置的EndPoint。 也許有辦法通過傳遞一個配置節來輕鬆創建EndPoint和Binding對象嗎?

回答

2

有2個選項。

選項1.使用頻道。

如果您是直接使用渠道,.NET 4.0和.NET 4.5有ConfigurationChannelFactory。在MSDN的例子是這樣的:

var factory1 = new ConfigurationChannelFactory<ICalculatorChannel>(
     "endpoint1", 
     newConfiguration, 
     null); 
ICalculatorChannel client1 = factory1.CreateChannel(); 

這是討論:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); 
fileMap.ExeConfigFilename = "Test.config"; 
Configuration newConfiguration = ConfigurationManager.OpenMappedExeConfiguration(
    fileMap, 
    ConfigurationUserLevel.None); 

ConfigurationChannelFactory<ICalculatorChannel> factory1 = 
    new ConfigurationChannelFactory<ICalculatorChannel>(
     "endpoint1", 
     newConfiguration, 
     new EndpointAddress("http://localhost:8000/servicemodelsamples/service")); 
ICalculatorChannel client1 = factory1.CreateChannel(); 

正如蘭登指出的那樣,你可以通過簡單地傳入null,這樣從配置文件中使用的端點地址在MSDN documentation

選項2.使用代理。

如果您使用的是代碼生成代理,那麼您可以讀取配置文件並加載ServiceModelSectionGroup。除了簡單地使用ConfigurationChannelFactory之外,還有一點工作要做,但至少您可以繼續使用生成的代理(該代理使用ChannelFactory併爲您管理IChannelFactory

巴勃羅Cibraro所示的是這方面的一個很好的例子:Getting WCF Bindings and Behaviors from any config source

+2

起初我感到失望,因爲構造函數需要你定義一個的EndpointAddress,其端點已經定義了,然後我意識到,你可以發送`null`和它會使用配置的地址。感謝發佈! – Langdon 2013-04-18 13:01:39

相關問題