Editar

Partilhar via


ServiceContractAttribute Class

Definition

Indicates that an interface or a class defines a service contract in a Windows Communication Foundation (WCF) application.

public ref class ServiceContractAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)]
public sealed class ServiceContractAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)>]
type ServiceContractAttribute = class
    inherit Attribute
Public NotInheritable Class ServiceContractAttribute
Inherits Attribute
Inheritance
ServiceContractAttribute
Attributes

Examples

The following code example shows how to apply the ServiceContractAttribute to an interface to define a service contract with one service method, indicated by the OperationContractAttribute. In this case, the protection level required of bindings for all messages is ProtectionLevel.EncryptAndSign.

The code example then implements that contract on the SampleService class.

using System;
using System.Collections.Generic;
using System.Net.Security;
using System.ServiceModel;
using System.Text;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(
    Namespace="http://microsoft.wcf.documentation",
    Name="SampleService",
    ProtectionLevel=ProtectionLevel.EncryptAndSign
  )]
  public interface ISampleService{
    [OperationContract]
    string SampleMethod(string msg);
  }

  class SampleService : ISampleService
  {
  #region ISampleService Members

  public string  SampleMethod(string msg)
  {
      return "The service greets you: " + msg;
  }

  #endregion
  }
}


Imports System.Collections.Generic
Imports System.Net.Security
Imports System.ServiceModel
Imports System.Text

Namespace Microsoft.WCF.Documentation
  <ServiceContract(Namespace:="http://microsoft.wcf.documentation", Name:="SampleService", ProtectionLevel:=ProtectionLevel.EncryptAndSign)> _
  Public Interface ISampleService
    <OperationContract> _
    Function SampleMethod(ByVal msg As String) As String
  End Interface

  Friend Class SampleService
      Implements ISampleService
  #Region "ISampleService Members"

  Public Function SampleMethod(ByVal msg As String) As String Implements ISampleService.SampleMethod
       Return "The service greets you: " & msg
  End Function

  #End Region
  End Class
End Namespace

The following code example shows a simple configuration file for the preceding service that creates one endpoint.

<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="mex"
      >
        <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="mex">
          <serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

The following code example shows a simple client that invokes the preceding SampleService.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

public class Client
{
  public static void Main()
  {
    // Picks up configuration from the config file.
    SampleServiceClient wcfClient = new SampleServiceClient();
    try
    {
        // Making calls.
        Console.WriteLine("Enter the greeting to send: ");
        string greeting = Console.ReadLine();
        Console.WriteLine("The service responded: " + wcfClient.SampleMethod(greeting));

        Console.WriteLine("Press ENTER to exit:");
        Console.ReadLine();

        // Done with service.
        wcfClient.Close();
        Console.WriteLine("Done!");
    }
    catch (TimeoutException timeProblem)
    {
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      wcfClient.Abort();
      Console.Read();
    }
    catch(CommunicationException commProblem)
    {
      Console.WriteLine("There was a communication problem. " + commProblem.Message);
      wcfClient.Abort();
      Console.Read();
    }
  }
}


Imports System.ServiceModel
Imports System.ServiceModel.Channels

Public Class Client
  Public Shared Sub Main()
    ' Picks up configuration from the config file.
    Dim wcfClient As New SampleServiceClient()
    Try
        ' Making calls.
        Console.WriteLine("Enter the greeting to send: ")
            Dim greeting = Console.ReadLine()
        Console.WriteLine("The service responded: " & wcfClient.SampleMethod(greeting))

        Console.WriteLine("Press ENTER to exit:")
        Console.ReadLine()

        ' Done with service. 
        wcfClient.Close()
        Console.WriteLine("Done!")
    Catch timeProblem As TimeoutException
      Console.WriteLine("The service operation timed out. " & timeProblem.Message)
      wcfClient.Abort()
      Console.Read()
    Catch commProblem As CommunicationException
      Console.WriteLine("There was a communication problem. " & commProblem.Message)
      wcfClient.Abort()
      Console.Read()
    End Try
  End Sub
End Class

Remarks

Use the ServiceContractAttribute attribute on an interface (or class) to define a service contract. Then use the OperationContractAttribute attribute on one or more of the class (or interface) methods to define the contract's service operations. When the service contract is implemented and combined with a Bindings and an EndpointAddress object, the service contract is exposed for use by clients. For an overview of the process using simple examples, see Getting Started Tutorial. For more information about creating service contracts, see Designing and Implementing Services.

The information expressed by a ServiceContractAttribute and its interface is loosely related to the Web Services Description Language (WSDL) <portType> element. A service contract is used on the service side to specify what the service's endpoint exposes to callers. It is also used on the client side to specify the contract of the endpoint with which the client communicates and, in the case of duplex contracts, to specify the callback contract (using the CallbackContract property) that the client must implement in order to participate in a duplex conversation.

Note

An interface or class that is decorated with ServiceContractAttribute must also have at least one method marked with the OperationContractAttribute attribute to expose any functionality. See the Examples section for a code example of the simplest use of the two attributes to define and implement a service.

Use the ServiceContractAttribute properties to modify the service contract.

  • The ConfigurationName property specifies the name of the service element in the configuration file to use.

  • The Name and Namespace properties control the name and namespace of the contract in the WSDL <portType> element.

  • The SessionMode property specifies whether the contract requires a binding that supports sessions.

  • The CallbackContract property specifies the return contract in a two-way (duplex) conversation.

  • The HasProtectionLevel and ProtectionLevel properties indicate whether all messages supporting the contract have a explicit ProtectionLevel value, and if so, what that level is.

Services implement service contracts, which represent the data exchange that a service type supports. A service class can implement a service contract (by implementing an interface marked with ServiceContractAttribute that has methods marked with OperationContractAttribute) or it can be marked with the ServiceContractAttribute and apply the OperationContractAttribute attribute to its own methods. (If a class implements an interface marked with ServiceContractAttribute, it cannot be itself marked with ServiceContractAttribute.) Methods on service types that are marked with the OperationContractAttribute are treated as part of a default service contract specified by the service type itself. For details about service operations, see OperationContractAttribute.

By default, the Name and Namespace properties are the name of the contract type and http://tempuri.org, respectively, and ProtectionLevel is ProtectionLevel.None. It is recommended that service contracts explicitly set their names, namespaces, and protection levels using these properties. Doing so accomplishes two goals. First, it builds a contract that is not directly connected to the managed type information, enabling you to refactor your managed code and namespaces without breaking the contract as it is expressed in WSDL. Second, explicitly requiring a certain level of protection on the contract itself enables the runtime to validate whether the binding configuration supports that level of security, preventing poor configuration from exposing sensitive information. For more information about protection levels, see Understanding Protection Level.

To expose a service for use by client applications, create a host application to register your service endpoint with Windows Communication Foundation (WCF). You can host WCF services using Windows Activation Services (WAS), in console applications, Windows Service applications, ASP.NET applications, Windows Forms applications, or any other kind of application domain.

Hosting in the WAS is very similar to creating an ASP.NET application. For details, see How to: Host a WCF Service in IIS.

Clients either use the service contract interface (the interface marked with ServiceContractAttribute) to create a channel to the service or they use the client objects (which combine the type information of the service contract interface with the ClientBase<TChannel> class) to communicate with your service. For details on client channels to services, see the ChannelFactory<TChannel> class and WCF Client Overview.

Using a ServiceContractAttribute class or interface to inherit from another ServiceContractAttribute class or interface extends the parent contract. For example, if an IChildContract interface is marked with ServiceContractAttribute and inherited from another service contract interface, IParentContract, the IChildContract service contract contains the methods of both IParentContract and IChildContract. Extending contracts (whether on classes or interfaces) is very similar to extending managed classes and interfaces.

The most flexible approach to creating services is to define service contract interfaces first and then have your service class implement that interface. (This is also the simplest way to build your services if you must implement service contracts that have been defined by others.) Building services directly by marking a class with ServiceContractAttribute and its methods with OperationContractAttribute works when the service exposes only one contract (but that contract can be exposed by more than one endpoint).

Use the CallbackContract property to indicate another service contract that, when bound together with the original service contract, define a message exchange that can flow in two ways independently. For details, see CallbackContract.

Constructors

ServiceContractAttribute()

Initializes a new instance of the ServiceContractAttribute class.

Properties

CallbackContract

Gets or sets the type of callback contract when the contract is a duplex contract.

ConfigurationName

Gets or sets the name used to locate the service in an application configuration file.

HasProtectionLevel

Gets a value that indicates whether the member has a protection level assigned.

Name

Gets or sets the name for the <portType> element in Web Services Description Language (WSDL).

Namespace

Gets or sets the namespace of the <portType> element in Web Services Description Language (WSDL).

ProtectionLevel

Specifies whether the binding for the contract must support the value of the ProtectionLevel property.

SessionMode

Gets or sets whether sessions are allowed, not allowed or required.

TypeId

When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

Methods

Equals(Object)

Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode()

Returns the hash code for this instance.

(Inherited from Attribute)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute()

When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object)

When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

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

Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from 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.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Applies to

See also