dstr
dstr

Reputation: 8928

Programmatically adding BehaviorExtensionElement

I have a ServiceHost I'm creating programmatically and I'd like to add a Behaviour to it. I can add the Behaviour using host.Description.Behaviors.Add() but I couldn't find a way to add the BehaviorExtensionElement part. There is a host.Extensions collection but it accepts ServiceHostBase. Basically I want to translate this web.config part to code:

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceDebug includeExceptionDetailInFaults="false" />
          <errorHandler />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="errorHandler" type="MyService.ErrorHandlerBehaviorExtensionElement, MyService" />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>

Upvotes: 1

Views: 3187

Answers (1)

Jophy job
Jophy job

Reputation: 1964

Service Behaviors

Service behaviors, which implement IServiceBehavior, are the primary mechanism by which you modify the entire service runtime. There are three mechanisms for adding service behaviors to a service.

  1. Using an attribute on the service class. When a ServiceHost is constructed, the ServiceHost implementation uses reflection to discover the set of attributes on the type of the service. If any of those attributes are implementations of IServiceBehavior, they are added to the behaviors collection on ServiceDescription. This allows those behaviors to participate in the construction of the service run time.

  2. Programmatically adding the behavior to the behaviors collection on ServiceDescription. This can be accomplished with the following lines of code:

    ServiceHost host = new ServiceHost(/* Parameters */); host.Description.Behaviors.Add(/* Service Behavior */);

  3. Implementing a custom BehaviorExtensionElement that extends configuration. This enables the use of the service behavior from application configuration files.

So I think both adding Behaviors and BehaviorExtensionElement is not needed . also check : https://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior(v=vs.110).aspx

Upvotes: 1

Related Questions