Programmatically and globally adding a custom WCF client endpoint behavior extension

I need to add a custom behavior extension to my WCF client endpoints. I tried to do this through the configuration, but was bitten by the frequently mentioned error, where the WFC configuration cannot parse the type name correctly. Can I do this programmatically?

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

Can I get endpoints around the world and pre-add them (for example, in Global.asax), or are these endpoints created and temporarily discarded?

+13
wcf behavior
Jul 28 '09 at 15:48
source share
1 answer

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

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

The first line will check whether this behavior has been applied so as not to apply it twice. If it has not already been applied (calling .Find() returns null), you can programmatically add this behavior to your client class.

You need to do all this before calling the first service call, obviously. Once you do this, you will no longer be able to change the client.

Mark

+14
Jul 28 '09 at 16:08
source share



All Articles