Simple WCF. The simplest configuration.

By Mirek on (tags: WCF, categories: code, web)

The power of WCF is that it can be used to any kind of communication. All known old transmission protocols are covered by WCF and can be totally replaced by it.

 

Unfortunately the drawback of this flexibility is complicated configuration in case when we want to do something not standard.

In WCF 4.0 this has been a little simplified, so now when you want to do simple thing at least , you do not need to dig in to much into configuration net. Ok. let’s assume we want to expose a simple web service over HTTP with metadata exposing.

First we create an ASP.NET MVC application which will be host for the service. Then we add the class file which will be our service class and mark it with Service and Operation contract attributes.

   1: namespace MVCApp
   2: {
   3:     [ServiceContract]
   4:     public class SimpleService
   5:     {
   6:         [OperationContract]
   7:         public string SendMessage(string message)
   8:         {
   9:             return "Message " + message + " sent.";
  10:         }
  11:     }
  12: }

 

Then in Web.config file we add following section

 

   1: <system.serviceModel>
   2:   <behaviors>
   3:     <serviceBehaviors>
   4:       <behavior>
   5:         <serviceMetadata httpGetEnabled="true" />
   6:       </behavior>
   7:     </serviceBehaviors>
   8:   </behaviors>
   9:   <serviceHostingEnvironment multipleSiteBindingsEnabled="true" >
  10:     <serviceActivations >
  11:       <add service="MVCApp.SimpleService"  relativeAddress="SimpleService.svc"/>
  12:     </serviceActivations>
  13:   </serviceHostingEnvironment>
  14: </system.serviceModel>
 
Yes that is so simple. There is in fact no need to have service interface, instead you have to decorate you service class with contract attributes. There is also no need to have, one line markup, svc file. Let’s look at web.config line 11. The service is activated here and svc file is “emulated”. The behaviors section defines default behavior for all services in the application and here says that the services has to expose metadata information. It is useful for clients that does not know our service contract and want to create a proxy of our service.