WCF ChannelFactory configuration outside of App.config?

后端 未结 3 1780
故里飘歌
故里飘歌 2021-02-06 08:03

I\'ve got a Windows Service that makes use of a plugin system. I\'m using the following code in the plugin base class to provide a separate configuration per DLL (so it\'ll rea

3条回答
  •  臣服心动
    2021-02-06 08:23

    There are 2 options.

    Option 1. Working with channels.

    If you are working with channels directly, .NET 4.0 and .NET 4.5 has the ConfigurationChannelFactory. The example on MSDN looks like this:

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    fileMap.ExeConfigFilename = "Test.config";
    Configuration newConfiguration = ConfigurationManager.OpenMappedExeConfiguration(
        fileMap,
        ConfigurationUserLevel.None);
    
    ConfigurationChannelFactory factory1 = 
        new ConfigurationChannelFactory(
            "endpoint1", 
            newConfiguration, 
            new EndpointAddress("http://localhost:8000/servicemodelsamples/service"));
    ICalculatorChannel client1 = factory1.CreateChannel();
    

    As pointed out by Langdon, you can use the endpoint address from the configuration file by simply passing in null, like this:

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

    This is discussed in the MSDN documentation.

    Option 2. Working with proxies.

    If you're working with code-generated proxies, you can read the config file and load a ServiceModelSectionGroup. There is a bit more work involved than simply using the ConfigurationChannelFactory but at least you can continue using the generated proxy (that under the hood uses a ChannelFactory and manages the IChannelFactory for you.

    Pablo Cibraro shows a nice example of this here: Getting WCF Bindings and Behaviors from any config source

提交回复
热议问题