Sunday 27 March 2011

WCF tutorial part 02 - separating service from host

In this tutorial we're going to separate service from host. In my opinion it's a good pattern to have service separated from host.
Let's add a new project to solution and call it MyService
After this, drag IService.cs and Service.cs files from WCFHost to MyService project. Remove them from original WCFHost project.
Change namespace in those files to MyService.
Make interface and class publicly accessible by adding public modifier to their definitions.

Add reference in WCFHost project to MyService project:

Build WCFHost project, this should build MyService library and copy the dll file to WCFHost project.

We need to make few adjustments in our host, to compile it. Only this section contains changes:
- in line 2 we're updating service type to MyService.Service
- in line 6 we're updating type of interface used to MyService.IService

Uri baseAddress = new Uri("http://localhost:8000/Service");
ServiceHost serviceHost = new ServiceHost(typeof(MyService.Service), baseAddress);
try
{
 serviceHost.AddServiceEndpoint(
  typeof(MyService.IService),
  new WSHttpBinding(),
  "Service");

 ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
 smb.HttpGetEnabled = true;
 serviceHost.Description.Behaviors.Add(smb);

 serviceHost.Open();
 Console.WriteLine("The service is ready.");
 Console.WriteLine("Press <ENTER> to terminate service.");
 Console.ReadLine();

 serviceHost.Close();
} 
 
We should update service reference in our client project, in order to do this you should:
  1. set startup project mode to current selection, 
  2. start WCFHost,
  3. rightclick on Service References - ServiceReference in WCFClient project and choose "Update Reference"
  4. start WCFClient project - there should be no errors.
Congratulations - you're done.
You can download project from here: http://sites.google.com/site/terespl/files/WCFTutorialpart02.zip

No comments:

Post a Comment