Operation behavior(s) can be programmatically added either on the service or on the consumer side.
When you have an instance of the host, grab out the service description (host.Description), then find the endpoint which hosts the contract. In the list of operations of the contract there is a place where to add operation behaviors. Here is an example:
| host1.Description.Endpoints.Contract.Operations[M].Behaviors.Add(behavior); |
If you do not have host instance (for example hosting in IIS) then you should implement your custom host and perform the same action as described above.
If you want to add an operation behavior on the client side the official documentation is a bit confusing. Adding behavior before the factory is created is finde, but there is not description how to do that. One factory is opened by invoking of factory.CreateChannel(). If you ever implemented your own communication object this happens in OnCreateChannelmethod of your factory.
Anyhow, the behavior has to be added before you call factory.CreateChannel(), and that is after
factory = new ChannelFactory<IMyExtendedService>(binding, address);
So, here is the ultimate one-line-code solution:
Read the complete post at http://developers.de/blogs/damir_dobric/archive/2009/06/03/adding-behaviors-programmatically.aspx