ServiceBehaviorAttribute 類別

定義

指定服務合約實作的內部執行行為。Specifies the internal execution behavior of a service contract implementation.

public ref class ServiceBehaviorAttribute sealed : Attribute, System::ServiceModel::Description::IServiceBehavior
[System.AttributeUsage(System.AttributeTargets.Class)]
public sealed class ServiceBehaviorAttribute : Attribute, System.ServiceModel.Description.IServiceBehavior
type ServiceBehaviorAttribute = class
    inherit Attribute
    interface IServiceBehavior
Public NotInheritable Class ServiceBehaviorAttribute
Inherits Attribute
Implements IServiceBehavior
繼承
ServiceBehaviorAttribute
屬性
實作

範例

下列程式碼範例會示範 ServiceBehaviorAttribute 屬性。The following code example demonstrates the ServiceBehaviorAttribute properties. BehaviorService 類別會使用 ServiceBehaviorAttribute 屬性指出: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.

此外,位於作業層級的 OperationBehaviorAttribute 值表示 TxWork 方法會自動登記在流動異動中或建立新異動來執行工作,並且表示如果沒有發生未處理的例外狀況,則會自動認可這項異動。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.

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."
      );
    }
  }
}
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

基礎繫結程序必須支援流動異動,才能讓下列程式碼範例正確執行。The underlying binding must support flowed transactions for the following code example to execute properly. 例如,若要使用 WSHttpBinding 支援流動的交易,請透過程式碼或應用程式組態檔,將 TransactionFlow 屬性設定為 trueTo 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>

備註

ServiceBehaviorAttribute 屬性套用至服務實作,即可指定整個服務的執行行為。Apply the ServiceBehaviorAttribute attribute to a service implementation to specify service-wide execution behavior. (若要指定方法層級的執行行為,請使用 OperationBehaviorAttribute 屬性)。這個屬性只能套用至服務實現。(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 屬性是一種 Windows Communication Foundation (WCF)程式設計模型功能,可啟用開發人員原本就必須執行的一般功能。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. 如需下列部分屬性集之基礎執行時間屬性的詳細資訊,請參閱擴充 ServiceHost 和服務模型層For more information about the underlying runtime properties that some of the following properties set, see Extending ServiceHost and the Service Model Layer.

  • AddressFilterMode 屬性會指定發送器系統用來找出負責處理要求之端點的篩選條件類型。The AddressFilterMode property specifies the type of filter that the dispatcher system uses to locate the endpoint that handles requests.

  • 當通道關閉,而且服務已完成處理任何剩餘的訊息時,AutomaticSessionShutdown 屬性便會自動關閉工作階段。The AutomaticSessionShutdown property automatically closes the session when the channel is closed and the service has finished processing any remaining messages.

  • ConcurrencyMode 屬性會控制內部執行緒模型,以便支援可重新進入 (Reentrant) 或多執行緒服務的物件。The ConcurrencyMode property controls the internal threading model, enabling support for reentrant or multithreaded services.

  • ConfigurationName 屬性 (Property) 是用來宣告在組態檔中 name 項目之 <service> 屬性 (Attribute) 中所使用的名稱。The ConfigurationName property is used to declare a name for use in the name attribute of the <service> element in a configuration file.

  • IgnoreExtensionDataObject 屬性會讓執行階段略過不是處理訊息時所需要的額外序列化資訊。The IgnoreExtensionDataObject property enables the run time to ignore extra serialization information that is not required to process the message.

  • IncludeExceptionDetailInFaults 屬性會指定服務中未處理的例外狀況是否會當做 SOAP 錯誤傳回。The IncludeExceptionDetailInFaults property specifies whether unhandled exceptions in a service are returned as SOAP faults. 這種設定僅供偵錯用途。This is for debugging purposes only.

  • InstanceContextMode 屬性會指定是否要在與用戶端交換期間回收服務和其服務物件,以及在何時回收。The InstanceContextMode property specifies whether and when services and their service objects are to be recycled during an exchange with a client.

  • MaxItemsInObjectGraph 屬性會限制物件圖形中已序列化項目的數目。The MaxItemsInObjectGraph property to limit on the number of items in an object graph that are serialized.

  • NameNamespace 屬性會控制服務項目之 WSDL 運算式的名稱和命名空間。The Name and Namespace properties control the name and namespace for the WSDL expression of the service element.

  • ReleaseServiceInstanceOnTransactionComplete 屬性會指定是否會在異動完成時回收服務物件。The ReleaseServiceInstanceOnTransactionComplete property specifies whether the service object is recycled when a transaction completes.

  • TransactionAutoCompleteOnSessionClose 屬性會指定是否要在工作階段關閉時完成未完成的異動。The TransactionAutoCompleteOnSessionClose property specifies whether outstanding transactions are completed when the session closes.

  • TransactionIsolationLevel 屬性會指定合約支援的異動隔離等級。The TransactionIsolationLevel property specifies the transaction isolation level that the contract supports.

  • TransactionTimeout 屬性會指定異動必須在該段期間完成、否則就會中止的時間間隔。The TransactionTimeout property specifies the time period within which a transaction must complete or it aborts.

  • UseSynchronizationContext 屬性會指出是否要搭配使用者介面執行緒,自動同步處理傳入的方法呼叫。The UseSynchronizationContext property indicates whether to synchronize inbound method calls with the user interface thread automatically.

  • ValidateMustUnderstand 屬性會通知系統是否要確認已實際瞭解標示為 MustUnderstand 的 SOAP 標頭。The ValidateMustUnderstand property informs the system whether it should confirm that SOAP headers marked as MustUnderstand have, in fact, been understood.

IncludeExceptionDetailInFaults 屬性也可以使用應用程式組態檔來設定。The IncludeExceptionDetailInFaults property can also be set using an application configuration file. 如需詳細資訊,請參閱IncludeExceptionDetailInFaultsFor details, see IncludeExceptionDetailInFaults.

建構函式

ServiceBehaviorAttribute()

ServiceBehaviorAttribute 類別的新執行個體初始化。Initializes a new instance of the ServiceBehaviorAttribute class.

屬性

AddressFilterMode

取得或設定 AddressFilterMode,此物件會由發送器用來將傳入訊息傳送至正確的端點。Gets or sets the AddressFilterMode that is used by the dispatcher to route incoming messages to the correct endpoint.

AutomaticSessionShutdown

指定是否要在用戶端關閉輸出工作階段時,自動關閉工作階段。Specifies whether to automatically close a session when a client closes an output session.

ConcurrencyMode

取得或設定服務是支援單一執行緒、多重執行緒或可重新進入的呼叫。Gets or sets whether a service supports one thread, multiple threads, or reentrant calls.

ConfigurationName

取得或設定用來在應用程式組態檔中尋找服務項目的值。Gets or sets the value used to locate the service element in an application configuration file.

EnsureOrderedDispatch

取得或設定值,這個值會表示是否確保已排序的服務分派。Gets or sets a value that indicates whether the service ordered dispatch is ensured.

IgnoreExtensionDataObject

取得或設定值,這個值會指定是否要將未知的序列化資料傳送到網路上。Gets or sets a value that specifies whether to send unknown serialization data onto the wire.

IncludeExceptionDetailInFaults

取得或設定值,指定一般未處理的執行例外狀況 (要轉換為型別 FaultException<TDetail>ExceptionDetail),並傳送為錯誤訊息。Gets or sets a value that specifies that general unhandled execution exceptions are to be converted into a FaultException<TDetail> of type ExceptionDetail and sent as a fault message. 請只在開發期間將這個項目設定為 true,以針對服務進行疑難排解。Set this to true only during development to troubleshoot a service.

InstanceContextMode

取得或設定值,這個值會指出何時建立新的服務物件。Gets or sets the value that indicates when new service objects are created.

MaxItemsInObjectGraph

取得或設定已序列化之物件中允許的項目數目上限。Gets or sets the maximum number of items allowed in a serialized object.

Name

取得或設定 Web 服務描述語言 (WSDL) 中服務項目中的名稱屬性的值。Gets or sets the value of the name attribute in the service element in Web Services Description Language (WSDL).

Namespace

取得或設定 Web 服務描述語言 (WSDL) 中服務的目標命名空間值。Gets or sets the value of the target namespace for the service in Web Services Description Language (WSDL).

ReleaseServiceInstanceOnTransactionComplete

取得或設定值,這個值會指定是否在目前交易完成時釋放服務物件。Gets or sets a value that specifies whether the service object is released when the current transaction completes.

TransactionAutoCompleteOnSessionClose

取得或設定值,這個值會指定當目前工作階段在沒有錯誤的情況下關閉時,是否完成擱置的交易。Gets or sets a value that specifies whether pending transactions are completed when the current session closes without error.

TransactionIsolationLevel

指定在服務內建立之新異動、以及來自用戶端之傳入異動的異動隔離等級。Specifies the transaction isolation level for new transactions created inside the service, and incoming transactions flowed from a client.

TransactionTimeout

取得或設定異動必須完成的期間。Gets or sets the period within which a transaction must complete.

TypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。When implemented in a derived class, gets a unique identifier for this Attribute.

(繼承來源 Attribute)
UseSynchronizationContext

取得或設定值,這個值會指定是否使用目前的同步處理內容來選擇執行的執行緒。Gets or sets a value that specifies whether to use the current synchronization context to choose the thread of execution.

ValidateMustUnderstand

取得或設定值,這個值會指定系統或應用程式是否會強制執行 SOAP MustUnderstand 標頭處理。Gets or sets a value that specifies whether the system or the application enforces SOAP MustUnderstand header processing.

方法

Equals(Object)

傳回值,這個值指出此執行個體是否與指定的物件相等。Returns a value that indicates whether this instance is equal to a specified object.

(繼承來源 Attribute)
GetHashCode()

傳回此執行個體的雜湊碼。Returns the hash code for this instance.

(繼承來源 Attribute)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
GetWellKnownSingleton()

擷取會實作服務、並以該實作結果做為服務之單一執行個體的物件,如果沒有單一執行個體,則為 nullRetrieves an object that implements the service and that is used as the singleton instance of the service, or null if there is no singleton instance.

IsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(繼承來源 Attribute)
Match(Object)

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(繼承來源 Attribute)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
SetWellKnownSingleton(Object)

指定會實作服務、並以該實作結果做為服務之單一執行個體的物件。Specifies an object that implements the service and that is used as the singleton instance of the service.

ShouldSerializeConfigurationName()

傳回值,這個值表示 ConfigurationName 屬性是否已變更為非預設值且應該序列化。Returns a value that indicates whether the ConfigurationName property has changed from its default value and should be serialized.

ShouldSerializeReleaseServiceInstanceOnTransactionComplete()

傳回值,這個值表示 ReleaseServiceInstanceOnTransactionComplete 屬性是否已變更為非預設值且應該序列化。Returns a value that indicates whether the ReleaseServiceInstanceOnTransactionComplete property has changed from its default value and should be serialized.

ShouldSerializeTransactionAutoCompleteOnSessionClose()

傳回值,這個值表示 TransactionAutoCompleteOnSessionClose 屬性是否已變更為非預設值且應該序列化。Returns a value that indicates whether the TransactionAutoCompleteOnSessionClose property has changed from its default value and should be serialized.

ShouldSerializeTransactionIsolationLevel()

傳回值,這個值表示 TransactionIsolationLevel 屬性是否已變更為非預設值且應該序列化。Returns a value that indicates whether the TransactionIsolationLevel property has changed from its default value and should be serialized.

ShouldSerializeTransactionTimeout()

傳回值,這個值表示 TransactionTimeout 屬性是否已變更為非預設值且應該序列化。Returns a value that indicates whether the TransactionTimeout property has changed from its default value and should be serialized.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。Maps a set of names to a corresponding set of dispatch identifiers.

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。Retrieves the type information for an object, which can be used to get the type information for an interface.

(繼承來源 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。Provides access to properties and methods exposed by an object.

(繼承來源 Attribute)
IServiceBehavior.AddBindingParameters(ServiceDescription, ServiceHostBase, Collection<ServiceEndpoint>, BindingParameterCollection)

將自訂資料物件傳遞至支援此行為屬性的繫結。Passes custom data objects to the bindings that support the behavior properties.

IServiceBehavior.ApplyDispatchBehavior(ServiceDescription, ServiceHostBase)

將服務執行階段自訂成支援此行為屬性。Customizes the service run time to support the behavior properties.

IServiceBehavior.Validate(ServiceDescription, ServiceHostBase)

確認服務描述和服務主機可以支援此行為。Confirms that the service description and service host are capable of supporting the behavior.

適用於

另請參閱