Why would one use the ChannelFactory to instantiate a WCF proxy rather than a Service Reference?

后端 未结 3 1961
北荒
北荒 2021-01-05 07:23

There seem to be two ways to instantiate WCF service proxies described here. My question is why would one want to use the ChannelFactory to instantiate a WCF proxy and what

3条回答
  •  自闭症患者
    2021-01-05 07:53

    The first option uses configuration settings provided in the web.config / app.config files to instantiate a proxy, however in certain situations its not feasible to put these settings in that file, for example if your application needs to use a different binding (maybe HTTP vs Named Pipes) depending on the scenario, or possibly your application may not even have a .config file.

    The second option gives a lot more flexibility when creating proxies to programatically specify the configuration to use for each proxy as you instantiate it.


    To give a more concrete example, supposing you wish to use Named Pipes for communication if communicating with the local machine, and HTTP if communicating with a remote host:

    if (UseNamedPipes())
    {
        EndpointAddress address = new EndpointAddress("net.pipe://localhost/Simple/BankService");
        return ChannelFactory.CreateChannel(new NetNamedPipeBinding(), address);
    }
    else
    {
        EndpointAddress address = new EndpointAddress("http://localhost:8000/Simple/BankService");
        return ChannelFactory.CreateChannel(new BasicHttpBinding(), address);
    }
    

提交回复
热议问题