I am attempting to pass a string into a method and based on what string is passed in, either instantiate BasicHttpBinding or WSHttpBinding. The following if statement is in my code.
if(bindingObject == "basic")
{System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();}
else
{System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();
This code gives me the error
The name 'binding' does not exist in the current context
From my research it seems I have to use a common base class between the two service models if I want to use the variable named binding no matter which ServiceModel I need to use.
My question is, what is the common base class that would work? Or is there a way to do this. The closest I have found is System.ServiceModel.Channels.Binding but then I get the error such as
does not contain a definition for 'MaxBufferPoolSize' and no extension method 'MaxBufferPoolSize' accepting a first argument of tyep 'System.ServiceModel.Channels.Binding' could be found
The problem you're facing is because of scoping of local variables. According to C# specs for scoping from MSDN,
Scopes can be nested, and an inner scope may redeclare the meaning of a name from an outer scope (this does not, however, remove the restriction imposed by §1.20 that within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block).
Another from spec for identifiers scoping,
For each occurrence of a given identifier as a simple-name in an expression or declarator, within the local variable declaration space, immediately enclosing block, or switch-block of that occurrence, every other occurrence of the same identifier as a simple-name in an expression or declarator within the immediately enclosing block or switch-block must refer to the same entity. This rule ensures that the meaning of a name is always the same within a given block, switch block, for-, foreach- or using-statement, or anonymous function.
Now moving to the error you're facing:
BasicHttpBinding
is derived from HttpBindingBase which derived from Binding
and implement IBindingRuntimePreferences
.
WSHttpBinding
is dervied from WSHttpBindingBase which derived from Binding
and implement IBindingRuntimePreferences
.
But the property MaxBufferPoolSize
resides in HttpBindingBase and WsHttpBindingBase and not in their common parent Binding
or IBindingRuntimePreferences
. Which means you can not use a common class to represent these bindings. Rather you should use dynamic
as type which would bind the types at runtime instead of compile time.
Public dynamic GetBinding(string bindingObject)
{
if (bindingObject == "basic")
{
binding = new System.ServiceModel.BasicHttpBinding();
}
else
{
binding = new System.ServiceModel.WSHttpBinding();
}
return binding;
}