WCF Programming Methods


WCF supports a diversity programming methods. This article discusses the three most common methods of developing WCF services.
  • Declarative
  • Explicit
  • Configuration
Declarative programming is accomplished via attributes. These attributes are used to define the contracts and behavior of the services. 

[ServiceContract]
public interface IMyWCFService
{
    	[OperationContract]
    	string Operation1(string myvalue);
}
public class MyWCFService : IMyWCFService
{
    	public string Operation1(string myvalue)
    	{
		return "Hello: " + myvalue;
    	}
}
For declarative programming, the attributes are added as shown below with highlighting.
[ServiceContract (SessionMode = SessionMode.Required)]
public interface IMyWCFService
{
    	[OperationContract (IsOneWay = true)]
    	string Operation1(string myvalue);
}
public class MyWCFService : IMyWCFService
{
    	public string Operation1(string myvalue)
    	{
 		return "Hello: " + myvalue;
    	}
}
Explicit programming lets you work directly with all the main classes and interfaces provided by the WCF object model. The following provides a simple example.
class WCFApp
{
    	static void Main()
    	{
      		Uri uri = new Uri("address path");
      		AddressHeader ah = AddressHeader.CreateAddressHeader("Header Name", "About header ", null);
       		EndpointAddress ea = new EndpointAddress(new Uri("service URL"), ah);
       		ServiceHost sh = new ServiceHost(typeof("your service"), uri);
       		sh.Description.Endpoints.Add(new ServiceEndpoint(ContractDescription.GetContract(typeof("contract")), new WSHttpBinding(), ea));
       		sh.Open();  sh.Close();
   	}
}

Configuration
based programming does not need a recompile of the service. Its a pure XML file.
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

	<system.serviceModel>

    		<services>

      			<service name="MyWCFService" behaviorConfiguration="returnFaults">

        			<endpoint contract="IMyWCFService" binding="wsHttpBinding" address="http://localhost:1038/WCFDemoService/service.svc"></endpoint>

      			</service>

    		</services>

    		<behaviors>

      			<serviceBehaviors>

       				<behavior name="returnFaults">

<serviceMetadata
httpGetEnabled="true"></serviceMetadata>

        			</behavior>

      			</serviceBehaviors>

    		</behaviors>

  	</system.serviceModel>

  	<system.web>

    		<compilation debug="true"/>

</system.web>

</configuration>
 
The best approach for developing a service is normally a combination of all three methods. But we need to know how the execution order occurs.
First, attributes are applied.
Second, configuration settings are applied. This will override the attributes if there is a conflict.
Finally, the code is executed.
Hope this helps to clear up the basics of WCF Programming Methods.

Up Next
    Ebook Download
    View all
    Learn
    View all