Adding WCF custom service behaviors in config

Lately I have been working with a bit of WCF for a client, and one of the things I have had to do is to create a service behavior to handle some security things. However, due to the fact that this application needed to run in several different environments, it needed to have different configuration under different circumstances.

The real need was actually to be able to remove the behavior in some circumstances, and add it in some. But I didn’t really want to do it through a bunch of if-statements in my behavior. Instead I wanted it to be done through configuration so that I could turn it on and off using config transforms…

Ok, so how do we do this? Custom service behaviors can be added to a service in several ways. They can be added to the WCF host from code, added as an attribute (also in code) or set up from config. But how do we make it available in config? Well, it isn’t that hard. All you need is an extra class that inherits from BehaviorExtensionElement and overrides 1 method, the CreateBehavior() method, and one property, the BehaviorType property.

It is REALLY simple to implement

public class MyBehaviorExtensionElement : BehaviorExtensionElement
{
protected override object CreateBehavior()
{
return new MyCustomServiceBehavior();
}

public override Type BehaviorType
{
get { return typeof(MyCustomServiceBehavior); }
}
}

As you can see, it only needs the inheritance and a way to return the type of the extension as well as an instance of it. Once we have that in place, we can add a behavior extension in web.config as follows

<?xml version="1.0"?>
<configuration>
...
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="myBehavior"
type="MyNamespace.MyBehaviorExtensionElement, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
...
</configuration>

and then add it as a behavior like this

<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
...
</services>

<behaviors>
<serviceBehaviors>
<behavior>
<myBehavior /> <!-- Easy as! -->
</behavior>
</serviceBehaviors>
</behaviors>

<extensions>
...
</extensions>
</system.serviceModel>
</configuration>

And if you need to remove it in some configuration, just add a config transform that removes it. Or the other way around, leaving it off by default and adding it in deploy… Just remember that the default setting is what will be used when debugging. Transforms only apply when publishing the app…

That’s it! Just a quick tip this time!

Cheers!

Comments are closed