IServiceBehavior 인터페이스

정의

ServiceHostBase를 포함하여 전체 서비스에 사용자 지정 확장을 수정 또는 삽입하기 위한 메커니즘을 제공합니다.

public interface class IServiceBehavior
public interface IServiceBehavior
type IServiceBehavior = interface
Public Interface IServiceBehavior
파생

예제

다음 코드 예제에서는 구성 파일에 지정된 서비스 동작을 사용하여 서비스 애플리케이션에 사용자 지정 오류 처리기를 삽입하는 방법을 보여 줍니다. 이 예제에서 오류 처리기는 모든 예외를 catch한 후 사용자 지정 GreetingFault SOAP 오류로 변환하여 클라이언트에 반환합니다.

다음 IServiceBehavior 구현에서는 바인딩 매개 변수 개체를 추가하지 않고 각 System.ServiceModel.Dispatcher.IErrorHandler 속성에 사용자 지정 ChannelDispatcher.ErrorHandlers 개체를 추가한 후 서비스 동작이 적용되는 각 서비스 작업에 System.ServiceModel.FaultContractAttribute 형식의 GreetingFault가 있는지 확인합니다.

// This behavior modifies no binding parameters.
#region IServiceBehavior Members
public void AddBindingParameters(
  ServiceDescription description,
  ServiceHostBase serviceHostBase,
  System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
  System.ServiceModel.Channels.BindingParameterCollection parameters
)
{
  return;
}

// This behavior is an IErrorHandler implementation and
// must be applied to each ChannelDispatcher.
public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.");
  foreach(ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
  {
    chanDisp.ErrorHandlers.Add(this);
  }
}

// This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("Validate is called.");
  foreach (ServiceEndpoint se in description.Endpoints)
  {
    // Must not examine any metadata endpoint.
    if (se.Contract.Name.Equals("IMetadataExchange")
      && se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
      continue;
    foreach (OperationDescription opDesc in se.Contract.Operations)
    {
      if (opDesc.Faults.Count == 0)
        throw new InvalidOperationException(String.Format(
          "EnforceGreetingFaultBehavior requires a "
          + "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  "
          + "The \"{0}\" operation contains no FaultContractAttribute.",
          opDesc.Name)
        );
      bool gfExists = false;
      foreach (FaultDescription fault in opDesc.Faults)
      {
        if (fault.DetailType.Equals(typeof(GreetingFault)))
        {
          gfExists = true;
          continue;
        }
      }
      if (gfExists == false)
      {
        throw new InvalidOperationException(
"EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract."
        );
      }
    }
  }
}
#endregion
' This behavior modifies no binding parameters.
#Region "IServiceBehavior Members"
Public Sub AddBindingParameters(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase, ByVal endpoints As System.Collections.ObjectModel.Collection(Of ServiceEndpoint), ByVal parameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IServiceBehavior.AddBindingParameters
  Return
End Sub

' This behavior is an IErrorHandler implementation and 
' must be applied to each ChannelDispatcher.
Public Sub ApplyDispatchBehavior(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.ApplyDispatchBehavior
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.")
  For Each chanDisp As ChannelDispatcher In serviceHostBase.ChannelDispatchers
    chanDisp.ErrorHandlers.Add(Me)
  Next chanDisp
End Sub

' This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
Public Sub Validate(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.Validate
  Console.WriteLine("Validate is called.")
  For Each se As ServiceEndpoint In description.Endpoints
    ' Must not examine any metadata endpoint.
    If se.Contract.Name.Equals("IMetadataExchange") AndAlso se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex") Then
      Continue For
    End If
    For Each opDesc As OperationDescription In se.Contract.Operations
      If opDesc.Faults.Count = 0 Then
        Throw New InvalidOperationException(String.Format("EnforceGreetingFaultBehavior requires a " & "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  " & "The ""{0}"" operation contains no FaultContractAttribute.", opDesc.Name))
      End If
      Dim gfExists As Boolean = False
      For Each fault As FaultDescription In opDesc.Faults
        If fault.DetailType.Equals(GetType(GreetingFault)) Then
          gfExists = True
          Continue For
        End If
      Next fault
      If gfExists = False Then
        Throw New InvalidOperationException("EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract.")
      End If
    Next opDesc
  Next se
End Sub
#End Region

또한 이 예제에서 동작 클래스는 System.ServiceModel.Configuration.BehaviorExtensionElement를 구현한 후 이를 사용하여 다음 코드 예제에서처럼 애플리케이션 구성 파일에 서비스 동작을 삽입할 수 있도록 합니다.

<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="metaAndErrors">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
         />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metaAndErrors">
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceMetadata httpGetEnabled="true"/>
          <enforceGreetingFaults />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add 
          name="enforceGreetingFaults" 
          type="Microsoft.WCF.Documentation.EnforceGreetingFaultBehavior, HostApplication, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
        />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>
</configuration>

설명

애플리케이션 수준에서 서비스 차원 실행의 일부 측면을 수정, 검사 또는 확장하기 위한 IServiceBehavior 인터페이스를 구현합니다.

  • 런타임 속성 값을 변경하거나 사용자 지정 확장명 개체(예: 오류 처리기, 메시지, 매개 변수 인터셉터 등), 보안 확장명 및 기타 사용자 지정 확장명 개체를 삽입하려면 ApplyDispatchBehavior 메서드를 사용합니다.

  • 사용 된 Validate Windows Communication Foundation (WCF) 올바르게 실행할 수 있는지 확인 하려면 실행 서비스를 생성 하기 전에 설명을 검사 하는 방법입니다.

  • 바인딩 요소에 서비스에 대한 사용자 지정 정보를 전달하여 서비스를 정확하게 지원할 수 있도록 하려면 AddBindingParameters 메서드를 사용합니다.

IServiceBehavior 개체는 이러한 메서드 중 아무 메서드나 사용할 수 있지만 그 중 하나만 사용되는 경우가 많으며 사용되지 않은 나머지 메서드는 값 없이 반환될 수 있습니다.

참고

모든 IServiceBehavior 메서드는 System.ServiceModel.Description.ServiceDescriptionSystem.ServiceModel.ServiceHostBase 개체를 매개 변수로 전달합니다. ServiceDescription 매개 변수는 검사 전용이므로 개체를 수정할 경우 실행 동작이 정의되지 않습니다.

원하는 대상에 서비스 사용자 지정 작업을 수행하려면 서비스 런타임을 생성하기 전에 IServiceBehavior 속성에 Behaviors 개체를 추가해야 합니다. 이때 다음과 같은 세 가지 방법을 사용할 수 있습니다.

WCF의 서비스 동작의 예로 ServiceBehaviorAttribute 특성인을 System.ServiceModel.Description.ServiceThrottlingBehavior, System.ServiceModel.Description.ServiceDebugBehaviorSystem.ServiceModel.Description.ServiceMetadataBehavior 동작 합니다.

메서드

AddBindingParameters(ServiceDescription, ServiceHostBase, Collection<ServiceEndpoint>, BindingParameterCollection)

계약 구현을 지원하는 사용자 지정 데이터를 바인딩 요소에 전달하는 기능을 제공합니다.

ApplyDispatchBehavior(ServiceDescription, ServiceHostBase)

런타임 속성 값을 변경하거나 사용자 지정 확장명 개체(예: 오류 처리기, 메시지, 매개 변수 인터셉터 등), 보안 확장명 및 기타 사용자 지정 확장명 개체를 삽입하는 기능을 제공합니다.

Validate(ServiceDescription, ServiceHostBase)

서비스 호스트와 서비스 설명을 검사하여 서비스가 성공적으로 실행될 수 있는지 확인하는 기능을 제공합니다.

적용 대상