Search code examples
c#wcfwcf-binding

How to programmatically declare different WCF Binding type depending on an if condition?


I have a WinForms client that programatically connects to a WCF service. This is how the connection variables are declared...

var myBinding = new NetTcpBinding(); 
var myEndpoint = new EndpointAddress(myURI); 
var myChannelFactory = new ChannelFactory<IService>(myBinding, myEndpoint);

However, I want to change it so that I can define "myBinding" (the same variable name) using different classes (not just NetTcpBinding) depending on the result of an if statement.

This is what I want (I know it doesn't work, but please try to understand my intent)

if (bindingType == "BasicHttpBinding") { var myBinding = new BasicHttpBinding(); }
if (bindingType == "NetTcpBinding") { var myBinding = new NetTcpBinding(); }
if (bindingType == "WSHttpBinding") { var myBinding = new WSHttpBinding(); }

Can anyone tell me how to achieve the same result with a method that works? Again, what I want is to be able to define "myBinding" depending on the result of an if statement. I'm also open to considering alternative suggestions. Thanks


Solution

  • I can't guarantee this will work, but try declaring myBinding as the base class.

    string bindingType = "BasicHttpBinding";
    System.ServiceModel.Channels.Binding myBinding;
    
    if (bindingType == "BasicHttpBinding") { myBinding = new BasicHttpBinding(); }
    if (bindingType == "NetTcpBinding") { myBinding = new NetTcpBinding(); }
    if (bindingType == "WSHttpBinding") { myBinding = new WSHttpBinding(); }