Implementing the HelloWorldService service contract

Now that we have defined a service contract interface, we need to implement it. For this purpose, we will re-use the empty class file that Visual Studio created for us earlier, and modify this to make it the implementation class of our service.

Before we modify this file, we need to rename it. In the Solution Explorer window, right-click on the file Class1.cs, select rename from the context menu, and rename it to HelloWorldService.cs.

Note

Visual Studio is smart enough to change all related files, references to use this new name. You can also select the file, and change its name from the Properties window.

Next, follow the steps below to customize this class file.

  1. Change its namespace from HelloWorldService to MyWCFServices. This is because this file was added before we changed the default namespace of the project.
  2. Make it inherit from the interface IHelloWorldService.
    public class HelloWorldService: IHelloWorldService
    
  3. Add a GetMessage method to the class. This is an ordinary C# method that returns a string.
    public String GetMessage(String name)
    {
    return "Hello world from " + name + "!";
    }
    

The final content of the file HelloWorldService.cs should look like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWCFServices
{
public class HelloWorldService: IHelloWorldService
{
public String GetMessage(String name)
{
return "Hello world from " + name + "!";
}
}
}

Now, build the project. If there is no build error, it means that you have successfully created your first WCF service. If you see a compilation error, such as "'ServiceModel' does not exist in the namespace 'System'", this is probably because you didn't add the ServiceModel namespace reference correctly. Revisit the previous section to add this reference, and you are all set.

Next, we will host this WCF service in an environment and create a client application to consume it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset