WCF Crib Sheet – Service Contract and Operation Contract

Service Contract Attribute

[ServiceContract]
public interface IProductService
{
   ...
}
  • Defines a WCF service contract.
  • Can be applied to an interface or a class. Best practice is to apply it to an interface.
  • WCF requires a class to have a parameter-less constructor.

Service Contract Names and Namespaces

[ServiceContract(Name="IBikeProductService", Namespace="BikeStore.WcfServiceLibrary")]
public interface IProductService
{     
    ...
}
  • Add a namespace to a service contract avoid potential class name collisions
  • Use the name property to change the name of the contract exposed to clients

Contract Inheritance

[ServiceContract(Namespace="BikeStore.WcfServiceLibrary")]
public interface IContractService
{
        ...
}

[ServiceContract(Namespace = "BikeStore.WcfServiceLibrary")]
public interface IPrepaymentContractService : IContractService
{
    ...
}
  • The service contract attribute is not inheritable and so must be added to all levels in a hierarchy.

Operation Contract Attribute

[ServiceContract]
public interface IProductService
{
    [OperationContract]
    ProductDto GetById(int productId);

    [OperationContract]
    IEnumerable<ProductDto> GetAll();
}
  • Indicates that a method defines an operation that is part of a service contract.
  • Methods without the attribute are not part of the service contract.
  • Can be applied to public and private methods.

Operation Overloading

[ServiceContract(Namespace="BikeStore.WcfServiceLibrary")]
public interface IProductService
{
    [OperationContract(Name="GetById")]
    ProductDto Get(int productId);

    [OperationContract(Name="GetByName")]
    ProductDto Get(string name);

    [OperationContract]
    IEnumerable<ProductDto> GetAll();
}
  • Operation names must be unique. Where the interface has overloaded methods, use the operation contract name property to alias the operation.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s