Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically and globally adding a custom WCF client endpoint behavior extension

Tags:

wcf

behavior

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?

like image 553
Trinition Avatar asked Jul 28 '09 15:07

Trinition


1 Answers

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

like image 135
marc_s Avatar answered Sep 24 '22 09:09

marc_s