ServiceBehaviorAttribute 類別

定義

指定服務合約實作的內部執行行為。

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

範例

下列程式碼範例會示範 ServiceBehaviorAttribute 屬性。 BehaviorService 類別會使用 ServiceBehaviorAttribute 屬性指出:

  • 此服務物件會在異動完成時回收。

  • 每個工作階段都有一個服務物件。

  • 該服務為單一執行緒服務,而且不支援可重新進入的呼叫。

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

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

基礎繫結必須支援流動交易,才能讓下列程式碼範例正確執行。 例如,若要使用 WSHttpBinding 支援流動的交易,請透過程式碼或應用程式組態檔,將 TransactionFlow 屬性設定為 true。 下列程式碼範例會顯示先前範例的組態檔。

<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 屬性套用至服務實作,即可指定整個服務的執行行為。 (若要在方法層級指定執行行為,請使用 OperationBehaviorAttribute attribute.) 此屬性只能套用至服務實作。 如需運作範例,請參閱 服務:行為範例

ServiceBehaviorAttribute 屬性是 Windows Communication Foundation (WCF) 程式設計模型功能,可讓開發人員必須實作的通用功能。 如需這些和其他行為的詳細資訊,請參閱 指定服務 Run-Time 行為。 如需下列部分屬性集之基礎執行時間屬性的詳細資訊,請參閱 擴充 ServiceHost 和服務模型層

IncludeExceptionDetailInFaults 屬性也可以使用應用程式組態檔來設定。 如需詳細資訊,請參閱 IncludeExceptionDetailInFaults

建構函式

ServiceBehaviorAttribute()

初始化 ServiceBehaviorAttribute 類別的新執行個體。

屬性

AddressFilterMode

取得或設定 AddressFilterMode,此物件會由發送器用來將傳入訊息傳送至正確的端點。

AutomaticSessionShutdown

指定是否要在用戶端關閉輸出工作階段時,自動關閉工作階段。

ConcurrencyMode

取得或設定服務是支援單一執行緒、多重執行緒或可重新進入的呼叫。

ConfigurationName

取得或設定用來在應用程式組態檔中尋找服務項目的值。

EnsureOrderedDispatch

取得或設定值,這個值會表示是否確保已排序的服務分派。

IgnoreExtensionDataObject

取得或設定值,這個值會指定是否要將未知的序列化資料傳送到網路上。

IncludeExceptionDetailInFaults

取得或設定值,指定一般未處理的執行例外狀況 (要轉換為型別 FaultException<TDetail>ExceptionDetail),並傳送為錯誤訊息。 請只在開發期間將這個項目設定為 true,以針對服務進行疑難排解。

InstanceContextMode

取得或設定值,這個值會指出何時建立新的服務物件。

MaxItemsInObjectGraph

取得或設定已序列化之物件中允許的項目數目上限。

Name

取得或設定 Web 服務描述語言 (WSDL) 中服務項目中的名稱屬性的值。

Namespace

取得或設定 Web 服務描述語言 (WSDL) 中服務的目標命名空間值。

ReleaseServiceInstanceOnTransactionComplete

取得或設定值,這個值會指定是否在目前異動完成時釋放服務物件。

TransactionAutoCompleteOnSessionClose

取得或設定值,這個值會指定當目前工作階段在沒有錯誤的情況下關閉時,是否完成擱置的交易。

TransactionIsolationLevel

指定在服務內建立之新交易、以及來自用戶端之傳入交易的交易隔離等級。

TransactionTimeout

取得或設定異動必須完成的期間。

TypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。

(繼承來源 Attribute)
UseSynchronizationContext

取得或設定值,這個值會指定是否使用目前的同步處理內容來選擇執行的執行緒。

ValidateMustUnderstand

取得或設定值,這個值會指定系統或應用程式是否會強制執行 SOAP MustUnderstand 標頭處理。

方法

Equals(Object)

傳回值,這個值指出此執行個體是否與指定的物件相等。

(繼承來源 Attribute)
GetHashCode()

傳回這個執行個體的雜湊碼。

(繼承來源 Attribute)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
GetWellKnownSingleton()

擷取會實作服務、並以該實作結果做為服務之單一執行個體的物件,如果沒有單一執行個體,則為 null

IsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。

(繼承來源 Attribute)
Match(Object)

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。

(繼承來源 Attribute)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
SetWellKnownSingleton(Object)

指定會實作服務、並以該實作結果做為服務之單一執行個體的物件。

ShouldSerializeConfigurationName()

傳回值,這個值表示 ConfigurationName 屬性是否已變更為非預設值且應該序列化。

ShouldSerializeReleaseServiceInstanceOnTransactionComplete()

傳回值,這個值表示 ReleaseServiceInstanceOnTransactionComplete 屬性是否已變更為非預設值且應該序列化。

ShouldSerializeTransactionAutoCompleteOnSessionClose()

傳回值,這個值表示 TransactionAutoCompleteOnSessionClose 屬性是否已變更為非預設值且應該序列化。

ShouldSerializeTransactionIsolationLevel()

傳回值,這個值表示 TransactionIsolationLevel 屬性是否已變更為非預設值且應該序列化。

ShouldSerializeTransactionTimeout()

傳回值,這個值表示 TransactionTimeout 屬性是否已變更為非預設值且應該序列化。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

明確介面實作

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

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。

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

擷取物件的類型資訊,可以用來取得介面的類型資訊。

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

擷取物件提供的類型資訊介面數目 (0 或 1)。

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

提供物件所公開的屬性和方法的存取權。

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

將自訂資料物件傳遞至支援此行為屬性的繫結。

IServiceBehavior.ApplyDispatchBehavior(ServiceDescription, ServiceHostBase)

將服務執行階段自訂成支援此行為屬性。

IServiceBehavior.Validate(ServiceDescription, ServiceHostBase)

確認服務描述和服務主機可以支援此行為。

適用於

另請參閱