Tuesday 13 September 2011

WCF Service Creation Quick Guide

What do web services allow you to do?

seperate out the different tiers of your application
encapsulate several processes into a single service, ready for consumption by an external party

Why are services beneficial

the seperation of concerns, although not unique to service-orientated architecture, allows for fault tolerance, in that if one aspect of an application or organisation goes down, it has minimal impact on
other business units/concerns/applications.
it allows for easier maintenance as the single offending unit can be fixed/tested/deployed in isolation without interupting the other services


a service exposes one or more endpoints.
each endpoint exposes one or more service operations.
the endpoint defines:
* an address where the service can be found
* a binding that contains the infomration that a client must provide to the service
* and a contract that defines the functionality the service provides to the client

Steps in Creating a WCF Service
1. Define a contract
 - A contract defines what operations the service supports
 - An 'operation' => a web service method
 - A contract is created by defining an interface; each method in the interface corresponds to a specific service operation
 - Each interface (contract) must have the ServiceContractAttribute
 - Each operation (service method) must have the OperationContractAttribute
 - Methods can exist within the contract without having the OperationContractAttribute but they won't be exposed by the service

2. Implement the contract (interface)
 - Create a new class that implements the interface defined with the ServiceContractAttribute
 - Implement each method from the Interface that has the OperationContractAttribute

3. Host and Run the WCF Service
 - Create a base address for the service.
 - Create a service host for the service.
    * import the System.ServiceModel.Description namespace
    * create a new ServiceHost instance; pass the type of the Service you want to host and its base address to the ServiceHost constructor
        * eg new ServiceHost(typeof(MyService), serviceBaseAddress);
    * wrap the following in a try-catch block, which catches CommunicationException and Aborts the Host when caught
        1.     // add an endpoint that exposes the service
            selfHost.AddServiceEndpoint(
                typeof(IMyService),
                new WSHttpBinding(),
                "MyService");

        2.    // Enable metadata exchange.
        3.    // Open the service host
            selfHost.Open();

No comments:

Post a Comment