Programmatically and globally adding a custom WCF client endpoint behavior extension

StackOverflow https://stackoverflow.com/questions/1195022

  •  19-09-2019
  •  | 
  •  

Question

I have the need to add a custom behavior extension to my WCF client endpoints. I tried doing this through configuration, but have been bitten by the often-mentioned bug where WFC configuration can't parse the type name correctly. So can I do this programatically instead?

I can't modify the configuration sections at runtime because they are read-only. I know if I get ahold of an instance of a client proxy (i.e. ClientBase), I can add to its Endpoint.Behaviors an instance of my custom behavior. However, I would have to do this for each instance.

Can I get to the endpoints globally and pre-add them (e.g. in Global.asax), or are these endpoints instantiated and discarded transiently?

Was it helpful?

Solution

You should be able to add the behavior to the client in code something like this:

IMyEndpointBehavior behavior = client.Endpoint.Behaviors.Find<IMyEndpointBehavior>();

if(behavior == null)
{
   client.Endpoint.Behaviors.Add(new MyEndpointBehaviorImplementation());
}

The first line would check if that behavior has already been applied to avoid applying it twice. If it's not been applied already (the .Find() call returns null), then you can programmatically add that behavior to your client class.

You need to do all this before issuing the first call to the service, obviously. Once you've done that, you cannot change the client anymore.

Marc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top