Monday, July 25, 2011

WCF REST Request Processing Pipeline

Generally we dont feel the need to know what exactly happens under the hood when you specify a REST Endpoint  while hosting your REST Service , 
RouteTable.Routes.Add(new ServiceRoute("CustomerExperienceService", new StructureMapServiceHostFactory(), typeof(CustomerExperienceService)));

We take for granted that WCF Runtime will host the service endpoint for us and it will be work as expected.

But i encountered a scenario, wherein the service wont start/hosted at all due to a error.  It just didnt hit any of breakpoints in the ServiceContract constructor or any of the Operations (Methods) , surely something was wrong with ServiceHosting process.

Hence using Reflector, i decided to take on the challenge of deciphering the code that makes our lives so easy. "A picture is worth a thousand words",  hence  a  block diagram would make it easy to understand : 

One important learning that i would want to share here is that , because of    

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
            via the attributes on the <standardEndpoint> element below
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>

the runtime calls DispatcherBuilder.InitializeServiceHost() only when there is a request for a particular REST Service, pretty much same like Asp.Net application. 

And when DispatcherBuilder.InitializeServiceHost() calls DispatcherBuilder.BindOperations() , all of the operation contracts under a ServiceContract are looped to ensure that WCF is able to process any request that comes in. The appropriate Formatters (XML or DataContract Serializers) are identified for each of the Operations and a check is performed whether Serialization/Deserialization of parameters is possible or not. 

Hence in the scenario i mentioned in other post, if i comment out the Operation which accepts or returns the Customer Object, the Service was getting hosted fine without any errors.

To conclude :  while Hosting the REST Service, the WCF Runtime loops through all of the Operations (via  DispatcherBuilder.BindOperations() ) you have in a ServiceContract and as it goes along, it also makes sure that Serialization of parameters is possible so that it can process any subsequent requests. Only if this check is success , the service will be hosted otherwise you will  see the specific error without any breakpoints being hit on your ServiceContract.

1 comment:

  1. Bluehost is ultimately one of the best hosting provider for any hosting services you might need.