.NET Framework Class Library
ServiceBehaviorAttribute Class

Specifies the internal execution behavior of a service contract implementation.

Inheritance Hierarchy
SystemObject
   SystemAttribute
    System.ServiceModelServiceBehaviorAttribute

Namespace:   System.ServiceModel
Assembly:  System.ServiceModel (in System.ServiceModel.dll)
Syntax
<[%$TOPIC/ms554644_en-us_VS_110_2_0_0_0_0%]([%$TOPIC/ms554644_en-us_VS_110_2_0_0_0_1%].Class)> _
Public NotInheritable Class ServiceBehaviorAttribute _
	Inherits [%$TOPIC/ms554644_en-us_VS_110_2_0_0_0_2%] _
	Implements [%$TOPIC/ms554644_en-us_VS_110_2_0_0_0_3%]
[[%$TOPIC/ms554644_en-us_VS_110_2_0_1_0_0%]([%$TOPIC/ms554644_en-us_VS_110_2_0_1_0_1%].Class)]
public sealed class ServiceBehaviorAttribute : [%$TOPIC/ms554644_en-us_VS_110_2_0_1_0_2%], 
	[%$TOPIC/ms554644_en-us_VS_110_2_0_1_0_3%]
[[%$TOPIC/ms554644_en-us_VS_110_2_0_2_0_0%]([%$TOPIC/ms554644_en-us_VS_110_2_0_2_0_1%]::Class)]
public ref class ServiceBehaviorAttribute sealed : public [%$TOPIC/ms554644_en-us_VS_110_2_0_2_0_2%], 
	[%$TOPIC/ms554644_en-us_VS_110_2_0_2_0_3%]
[<[%$TOPIC/ms554644_en-us_VS_110_2_0_3_0_0%]>]
[<[%$TOPIC/ms554644_en-us_VS_110_2_0_3_0_1%]([%$TOPIC/ms554644_en-us_VS_110_2_0_3_0_2%].Class)>]
type ServiceBehaviorAttribute =  
    class 
        inherit [%$TOPIC/ms554644_en-us_VS_110_2_0_3_0_3%] 
        interface [%$TOPIC/ms554644_en-us_VS_110_2_0_3_0_4%] 
    end
public final class ServiceBehaviorAttribute extends [%$TOPIC/ms554644_en-us_VS_110_2_0_4_0_0%] implements [%$TOPIC/ms554644_en-us_VS_110_2_0_4_0_1%]

The ServiceBehaviorAttribute type exposes the following members.

Constructors
  NameDescription
Public method ServiceBehaviorAttributeInitializes a new instance of the ServiceBehaviorAttribute class.
Top
Properties
  NameDescription
Public property AddressFilterModeGets or sets the AddressFilterMode that is used by the dispatcher to route incoming messages to the correct endpoint.
Public property AutomaticSessionShutdownSpecifies whether to automatically close a session when a client closes an output session.
Public property ConcurrencyModeGets or sets whether a service supports one thread, multiple threads, or reentrant calls.
Public property ConfigurationNameGets or sets the value used to locate the service element in an application configuration file.
Public property EnsureOrderedDispatchGets or sets a value that indicates whether the service ordered dispatch is ensured.
Public property IgnoreExtensionDataObjectGets or sets a value that specifies whether to send unknown serialization data onto the wire.
Public property IncludeExceptionDetailInFaultsGets or sets a value that specifies that general unhandled execution exceptions are to be converted into a System.ServiceModelFaultExceptionTDetail of type System.ServiceModelExceptionDetail and sent as a fault message. Set this to true only during development to troubleshoot a service.
Public property InstanceContextModeGets or sets the value that indicates when new service objects are created.
Public property MaxItemsInObjectGraphGets or sets the maximum number of items allowed in a serialized object.
Public property NameGets or sets the value of the name attribute in the service element in Web Services Description Language (WSDL).
Public property NamespaceGets or sets the value of the target namespace for the service in Web Services Description Language (WSDL).
Public property ReleaseServiceInstanceOnTransactionCompleteGets or sets a value that specifies whether the service object is released when the current transaction completes.
Public property TransactionAutoCompleteOnSessionCloseGets or sets a value that specifies whether pending transactions are completed when the current session closes without error.
Public property TransactionIsolationLevelSpecifies the transaction isolation level for new transactions created inside the service, and incoming transactions flowed from a client.
Public property TransactionTimeoutGets or sets the period within which a transaction must complete.
Public property TypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Public property UseSynchronizationContextGets or sets a value that specifies whether to use the current synchronization context to choose the thread of execution.
Public property ValidateMustUnderstandGets or sets a value that specifies whether the system or the application enforces SOAP MustUnderstand header processing.
Top
Methods
  NameDescription
Public method EqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Public method GetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method GetWellKnownSingletonRetrieves an object that implements the service and that is used as the singleton instance of the service, or if there is no singleton instance.
Public method IsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public method MatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Public method SetWellKnownSingletonSpecifies an object that implements the service and that is used as the singleton instance of the service.
Public method ShouldSerializeConfigurationNameReturns a value that indicates whether the ConfigurationName property has changed from its default value and should be serialized.
Public method ShouldSerializeReleaseServiceInstanceOnTransactionCompleteReturns a value that indicates whether the ReleaseServiceInstanceOnTransactionComplete property has changed from its default value and should be serialized.
Public method ShouldSerializeTransactionAutoCompleteOnSessionCloseReturns a value that indicates whether the TransactionAutoCompleteOnSessionClose property has changed from its default value and should be serialized.
Public method ShouldSerializeTransactionIsolationLevelReturns a value that indicates whether the TransactionIsolationLevel property has changed from its default value and should be serialized.
Public method ShouldSerializeTransactionTimeoutReturns a value that indicates whether the TransactionTimeout property has changed from its default value and should be serialized.
Public method ToStringReturns a string that represents the current object. (Inherited from Object.)
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method _AttributeGetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeGetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeGetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeInvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Explicit interface implemetation Private method IServiceBehaviorAddBindingParametersPasses custom data objects to the bindings that support the behavior properties.
Explicit interface implemetation Private method IServiceBehaviorApplyDispatchBehaviorCustomizes the service run time to support the behavior properties.
Explicit interface implemetation Private method IServiceBehaviorValidateConfirms that the service description and service host are capable of supporting the behavior.
Top
Remarks

Apply the ServiceBehaviorAttribute attribute to a service implementation to specify service-wide execution behavior. (To specify execution behavior at the method level, use the OperationBehaviorAttribute attribute.) This attribute can be applied only to service implementations. For working examples, see the Service Behaviors Samples.

ServiceBehaviorAttribute properties are a Windows Communication Foundation (WCF) programming model feature that enables common features that developers otherwise have to implement. For more information about these and other behaviors, see Specifying Service Run-Time Behavior. For more information about the underlying runtime properties that some of the following properties set, see Extending ServiceHost and the Service Model Layer.

  • The AddressFilterMode property specifies the type of filter that the dispatcher system uses to locate the endpoint that handles requests.

  • The AutomaticSessionShutdown property automatically closes the session when the channel is closed and the service has finished processing any remaining messages.

  • The ConcurrencyMode property controls the internal threading model, enabling support for reentrant or multithreaded services.

  • The ConfigurationName property is used to declare a name for use in the name attribute of the <service> element in a configuration file.

  • The IgnoreExtensionDataObject property enables the run time to ignore extra serialization information that is not required to process the message.

  • The IncludeExceptionDetailInFaults property specifies whether unhandled exceptions in a service are returned as SOAP faults. This is for debugging purposes only.

  • The InstanceContextMode property specifies whether and when services and their service objects are to be recycled during an exchange with a client.

  • The MaxItemsInObjectGraph property to limit on the number of items in an object graph that are serialized.

  • The Name and Namespace properties control the name and namespace for the WSDL expression of the service element.

  • The ReleaseServiceInstanceOnTransactionComplete property specifies whether the service object is recycled when a transaction completes.

  • The TransactionAutoCompleteOnSessionClose property specifies whether outstanding transactions are completed when the session closes.

  • The TransactionIsolationLevel property specifies the transaction isolation level that the contract supports.

  • The TransactionTimeout property specifies the time period within which a transaction must complete or it aborts.

  • The UseSynchronizationContext property indicates whether to synchronize inbound method calls with the user interface thread automatically.

  • The ValidateMustUnderstand property informs the system whether it should confirm that SOAP headers marked as MustUnderstand have, in fact, been understood.

The IncludeExceptionDetailInFaults property can also be set using an application configuration file. For details, see IncludeExceptionDetailInFaults.

Examples

The following code example demonstrates the ServiceBehaviorAttribute properties. The BehaviorService class uses the ServiceBehaviorAttribute attribute to indicate that:

  • The service object is recycled when the transaction completes.

  • There is one service object for each session.

  • The service is single-threaded and does not support reentrant calls.

Furthermore, at the operation level, the OperationBehaviorAttribute values indicate that the TxWork method automatically enlists in flowed transactions or creates a new transaction to do the work, and that the transaction is committed automatically if an unhandled exception does not occur.

Imports System.ServiceModel
Imports System.Transactions

Namespace Microsoft.WCF.Documentation
  <ServiceContract(Namespace:="http://microsoft.wcf.documentation", SessionMode:=SessionMode.Required)> _
  Public Interface IBehaviorService
	<OperationContract> _
	Function TxWork(ByVal message As String) As String 
  End Interface 

  ' Note: To use the TransactionIsolationLevel property, you  
  ' must add a reference to the System.Transactions.dll assembly. 
'   The following service implementation: 
'   *   -- Processes messages on one thread at a time 
'   *   -- Creates one service object per session 
'   *   -- Releases the service object when the transaction commits 
'   
    <ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Single, InstanceContextMode:=InstanceContextMode.PerSession, _
                     ReleaseServiceInstanceOnTransactionComplete:=True)> _
    Public Class BehaviorService
        Implements IBehaviorService, IDisposable
        Private myID As Guid

        Public Sub New()
            myID = Guid.NewGuid()
            Console.WriteLine("Object " & myID.ToString() & " created.")
        End Sub 

        '     
        '     * The following operation-level behaviors are specified: 
        '     *   -- The executing transaction is committed when 
        '     *        the operation completes without an  
        '     *        unhandled exception 
        '     *   -- Always executes under a flowed transaction. 
        '     
        <OperationBehavior(TransactionAutoComplete:=True, TransactionScopeRequired:=True), TransactionFlow(TransactionFlowOption.Mandatory)> _
        Public Function TxWork(ByVal message As String) As String Implements IBehaviorService.TxWork
            ' Do some transactable work.
            Console.WriteLine("TxWork called with: " & message)
            ' Display transaction information. 

            Dim info As TransactionInformation = Transaction.Current.TransactionInformation
            Console.WriteLine("The distributed tx ID: {0}.", info.DistributedIdentifier)
            Console.WriteLine("The tx status: {0}.", info.Status)
            Return String.Format("Hello. This was object {0}.", myID.ToString())
        End Function 

        Public Sub Dispose() Implements IDisposable.Dispose
            Console.WriteLine("Service " & myID.ToString() & " is being recycled.")
        End Sub 
    End Class 
End Namespace
using System;
using System.ServiceModel;
using System.Transactions;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(
    Namespace="http://microsoft.wcf.documentation", 
    SessionMode=SessionMode.Required
  )]
  public interface IBehaviorService
  {
    [OperationContract]
    string TxWork(string message);
  }

  // Note: To use the TransactionIsolationLevel property, you  
  // must add a reference to the System.Transactions.dll assembly. 
  /* The following service implementation:
   *   -- Processes messages on one thread at a time
   *   -- Creates one service object per session
   *   -- Releases the service object when the transaction commits
   */
  [ServiceBehavior(
    ConcurrencyMode=ConcurrencyMode.Single,
    InstanceContextMode=InstanceContextMode.PerSession,
    ReleaseServiceInstanceOnTransactionComplete=true
  )]
  public class BehaviorService : IBehaviorService, IDisposable
  {
    Guid myID;

    public BehaviorService()
    {
      myID = Guid.NewGuid();
      Console.WriteLine(
        "Object "
        + myID.ToString()
        + " created.");
    }

    /*
     * The following operation-level behaviors are specified:
     *   -- The executing transaction is committed when
     *        the operation completes without an 
     *        unhandled exception
     *   -- Always executes under a flowed transaction.
     */
    [OperationBehavior(
      TransactionAutoComplete = true,
      TransactionScopeRequired = true
    )]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public string TxWork(string message)
    {
      // Do some transactable work.
      Console.WriteLine("TxWork called with: " + message);
      // Display transaction information.

      TransactionInformation info = Transaction.Current.TransactionInformation;
      Console.WriteLine("The distributed tx ID: {0}.", info.DistributedIdentifier);
      Console.WriteLine("The tx status: {0}.", info.Status);
      return String.Format("Hello. This was object {0}.",myID.ToString()) ;
    }

    public void Dispose()
    {
      Console.WriteLine(
        "Service "
        + myID.ToString()
        + " is being recycled."
      );
    }
  }
}

The underlying binding must support flowed transactions for the following code example to execute properly. To support flowed transactions using the WSHttpBinding, for example, set the TransactionFlow property to true in code or in an application configuration file. The following code example shows the configuration file for the preceding sample.

<configuration>
  <system.serviceModel>
    <services>
      <service  
        name="Microsoft.WCF.Documentation.BehaviorService" 
        behaviorConfiguration="metadataAndDebugEnabled"
      >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <!--
          Note:
            This example code uses the WSHttpBinding to support transactions using the 
            WS-AtomicTransactions (WS-AT) protocol. WSHttpBinding is configured to use the  
            protocol, but the protocol is not enabled on some computers. Use the xws_reg -wsat+ 
            command to enable the WS-AtomicTransactions protocol in the MSDTC service.          
          -->
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="wsHttpBinding"
           bindingConfiguration="wsHttpBindingWithTXFlow"
           address="http://localhost:8080/BehaviorService"
          />
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="netTcpBinding"
           bindingConfiguration="netTcpBindingWithTXFlow"
           address="net.tcp://localhost:8081/BehaviorService"
          />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
        />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataAndDebugEnabled">
          <serviceDebug
            includeExceptionDetailInFaults="true"
          />
          <serviceMetadata
            httpGetEnabled="true"
            httpGetUrl=""
          />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- binding configuration - configures a WSHttpBinding to require transaction flow -->
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpBindingWithTXFlow" transactionFlow="true" />
      </wsHttpBinding>
      <netTcpBinding>
        <binding name="netTcpBindingWithTXFlow" transactionFlow="true" />
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
<configuration>
  <system.serviceModel>
    <services>
      <service  
        name="Microsoft.WCF.Documentation.BehaviorService" 
        behaviorConfiguration="metadataAndDebugEnabled"
      >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <!--
          Note:
            This example code uses the WSHttpBinding to support transactions using the 
            WS-AtomicTransactions (WS-AT) protocol. WSHttpBinding is configured to use the  
            protocol, but the protocol is not enabled on some computers. Use the xws_reg -wsat+ 
            command to enable the WS-AtomicTransactions protocol in the MSDTC service.          
          -->
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="wsHttpBinding"
           bindingConfiguration="wsHttpBindingWithTXFlow"
           address="http://localhost:8080/BehaviorService"
          />
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="netTcpBinding"
           bindingConfiguration="netTcpBindingWithTXFlow"
           address="net.tcp://localhost:8081/BehaviorService"
          />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
        />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataAndDebugEnabled">
          <serviceDebug
            includeExceptionDetailInFaults="true"
          />
          <serviceMetadata
            httpGetEnabled="true"
            httpGetUrl=""
          />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- binding configuration - configures a WSHttpBinding to require transaction flow -->
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpBindingWithTXFlow" transactionFlow="true" />
      </wsHttpBinding>
      <netTcpBinding>
        <binding name="netTcpBindingWithTXFlow" transactionFlow="true" />
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
<configuration>
  <system.serviceModel>
    <services>
      <service  
        name="Microsoft.WCF.Documentation.BehaviorService" 
        behaviorConfiguration="metadataAndDebugEnabled"
      >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <!--
          Note:
            This example code uses the WSHttpBinding to support transactions using the 
            WS-AtomicTransactions (WS-AT) protocol. WSHttpBinding is configured to use the  
            protocol, but the protocol is not enabled on some computers. Use the xws_reg -wsat+ 
            command to enable the WS-AtomicTransactions protocol in the MSDTC service.          
          -->
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="wsHttpBinding"
           bindingConfiguration="wsHttpBindingWithTXFlow"
           address="http://localhost:8080/BehaviorService"
          />
        <endpoint 
               contract="Microsoft.WCF.Documentation.IBehaviorService"
               binding="netTcpBinding"
               bindingConfiguration="netTcpBindingWithTXFlow"
               address="net.tcp://localhost:8081/BehaviorService"
          />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataAndDebugEnabled">
          <serviceDebug
            includeExceptionDetailInFaults="true"
          />
          <serviceMetadata
            httpGetEnabled="true"
            httpGetUrl=""
          />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- binding configuration - configures a WSHttpBinding to require transaction flow -->
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpBindingWithTXFlow" transactionFlow="true" />
      </wsHttpBinding>
      <netTcpBinding>
        <binding name="netTcpBindingWithTXFlow" transactionFlow="true" />
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
Version Information

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.