steverb.com

Things I Felt Like Posting

Passing Configuration Values into WCF Behaviors

Sometimes when creating a WCF behavior it'd be nice to be able to pass in some sort of instance specific configuration information. Fortunately, you can.

In the previous post we added a class that implemented BehaviorExtensionElement so that we could apply our IServiceBehavior via the config file. There are a few other methods that you can implement so that the BehaviorExtensionElement will pull settings from the config file. This way when you add the behavior you can tell it something special, like what the friendly name of the service is.

 

<serviceBehaviors>
        <behavior name="TrainingService.Service1Behavior">
          <AutoRegister ServiceName="TrainingService" />
        </behavior>
</serviceBehaviors>

Simply add a property to the behavior (IServiceBehavior in this instance), then in the class that implements BehaviorExtensionElement, add a property decorated with System.Configuration.ConfigurationProperty.

 

        [System.Configuration.ConfigurationProperty("ServiceName", DefaultValue = "", IsRequired = true)]
        public string ServiceName
        {
            get
            {
                return (string)base["ServiceName"];
            }
            set
            {
                base["ServiceName"] = value;
            }
        }

 

In this case, we are simply passing back to the IServiceBehavior.

 

Now add a ConfigurationPropertyCollection and a readonly PropertiesProperty

 

        private ConfigurationPropertyCollection _prop = null;
 
        protected override System.Configuration.ConfigurationPropertyCollection Properties
        {
            get
            {
                if (this._prop == null)
                {
                    this._prop = new System.Configuration.ConfigurationPropertyCollection();
                    this._prop.Add(new System.Configuration.ConfigurationProperty("ServiceName", typeof(string),
                        "", System.Configuration.ConfigurationPropertyOptions.IsRequired));
                }
                return this._prop;
            }
        }

Now your IServiceBehavior can get its property set.

Comments (1) -

Comments are closed