WCF - Part 2: Basic Client/Server app
This post is an example of how to build your first basicly wcf solution.
First step: Contract
Our contract is a simple interface class (ICalculator) containing one function: (Add).In order to declare the interface as a contract, you should add a [ServiceContract] attribute to the class. All methods you want to expose in your service, you should mark as [OperationContract].
1 2 3 4 5 6 |
[ServiceContract] public interface ICalculator { [OperationContract] int Add(int a,int b); } |
Second step: The server
The server should implement the contract simply by implementing the ICalculator interface as the following code:
1 2 3 4 5 6 7 8 9 |
public class Calculator : ICalculator { #region ICalculator Members public int Add(int a,int b) { return a + b ; } #endregion } |
Hosting the server: We'll do this using a C# console application. We need a ServiceHost object to host our service. It implements IDisposable, so we'll use the using statement to create one.
Explanations for the sample below :
- Declare a type variable, assign Calculator service contract type to it and pass it into the constructor of our ServiceHost instance.
- Open the service.
1 2 3 4 5 6 7 8 9 10 11 |
static void Main(string[] args) { Type type = typeof(Calculator); using (ServiceHost host = new ServiceHost(typeof(type))) { host.Open(); Console.WriteLine("The service is available.Press any key to continue..."); Console.ReadLine(); host.Close(); } } |
WCF needs some information from configuration; The server is configured to run using the ICalculator Contract, but I didn't specify neither the Address or the Binding. The App.Config file contains the Address and Binding as following:
We can generate the App.config using the SvcConfigEditor.exe tool under "\Program Files\Microsoft Visual Studio 8\Common7\IDE\".
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="Wcf.Samples.Calculator">
<endpoint
address="net.tcp://localhost:5555/Calculator/"
binding="netTcpBinding"
contract="Wcf.Samples.ICalculator"
bindingConfiguration="" />
</service>
</services>
</system.serviceModel>
</configuration>
Third step: The client
After the server is ready, we can build our client;
1 2 3 4 5 6 7 8 9 10 |
static void Main(string[] args) { using (ChannelFactory<ICalculator> claculatorFactory = new ChannelFactory<ICalculator>("MyClient")) { ICalculator calcProxy = claculatorFactory.CreateChannel(); int res = calcProxy.Add(1,2); Console.WriteLine(res); Console.ReadLine(); } } |
We can generate the App.config the same way we generated the server with the SvcConfigEditor.exe to get the following file:
<client>
<endpoint address="net.tcp://localhost:5555/Calculator" binding="netTcpBinding"
contract="Wcf.Samples.ICalculator"
name="MyClient" />
</client>
The application is ready to use.
Back to WCF TOC.