Saturday, November 27, 2010

WCF service in a Self Host Environment

Today I was trying to run a WCF service in a Self Host Environment.
I think this is one of the simplest way to test a WCF service.
Here is the steps I have done.

I took the VS2010 and created new Console project.

Created a service Contract as follows
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
string SayHello(string name);
}


Then I created the real Service implementing the Service Contract created.

public class HelloWorldService : IHelloWorldService
{

#region IHelloWorldService Members

public string SayHello(string name)
{
return string.Format("Hello, {0} ", name);
}

#endregion
}

Now here is the critical part.

In the Main Method write as follows
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8080/hello");
using(ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
{
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled= true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("This service is ready at {0}", baseAddress);
Console.WriteLine("Press to stop the service.");
Console.ReadLine();
host.Close();
}

First create an instance of ServiceHost.
Then create an instance of ServiceMetadataBehaviour, do necessary wiring
Now open the WCF Test client application (In Visual studio command prompt , type - wcftestclient.exe)
From the file - > Add Service , give the baseaddress (i. e http://localhost:8080/hello)

Now we will be able to see the Operation contracts listed there

The wiring that we had made in the Main method we will be able to see in the config format in WCT Test application.




Select the Operation node and test the application, you can also be able to see the payload of the requests.

No comments:

Post a Comment