I’ve already got a post on WCF basics, but I had to quickly knock together a WCF service and client to try something out today and I thought it’d be useful to list the steps to create a real bare bones service and client in a single post.
Let’s begin with the service itself. I want to create a self hosted service running from a console app. so I can easily debug and control everything, so
1. Open a new instance of Visual Studio
2. Create a new console application.
3. Copy the following into the Main method
ServiceHost serviceHost = new ServiceHost(typeof(MyService));
serviceHost.Open();
Console.WriteLine("Service Running");
Console.ReadLine();
serviceHost.Close();
4. Add the reference to System.ServiceModel as well as a valid app.config. For example
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfTest.MyService">
<endpoint address="" binding="netTcpBinding" bindingConfiguration=""
contract="WcfTest.IMyService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8732/MyService/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
5. Create an interface with at least one method, as we’re calling the service MyService, let’s call the interface IMyService. You’ll need at least one method and the interface shold have a ServiceContract attribute and the method have an OperationContract, for example
[ServiceContract]
public interface IMyService
{
[OperationContract]
void SayHello(string name);
}
6. Implement the interface for example
public class MyService : IMyService
{
public void SayHello(string name)
{
Console.WriteLine("Hello " + name);
}
}
6. Run the application
Now to the client…
1. Open a new instance of Visual Studio
2. Create a console application
3. Add a service reference (use the url from the server, i.e. net.tcp://localhost:8732/MyService/mex from the service’s app.config)
4. Click Go
5. Click OK
6. Finally add the following code into the Main method
var client = new MyServiceClient();
client.SayHello("Scooby Doo");
client.Close();
Now we have a working service and client.