Hosting a Declarative Service
Now that you have created the service, the next step is to host the service through a hosting application. For example purposes, a simple console application suffices to host the service.
class Program
{
static Service service;
static void Main()
{
Console.WriteLine("Loading WCF Service");
using (TextReader reader =
File.OpenText("HelloWorldService.xml"))
{
service = (Service)XamlServices.Load(reader);
}
Uri address = new
Uri("http://localhost:8000/HelloWorldService");
WorkflowServiceHost1 host = new
WorkflowServiceHost1(service, address);
try
{
Console.WriteLine("Opening Service");
host.Open();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(
"Service terminated with exception {0}", ex.ToString());
}
finally
{
host.Close();
}
}
}
The preceding code loads the XAML file by invoking the System.IO.File.OpenText() method, passing in the name of the XAML file that contains the service definition. Then it obtains a reference to the service by calling the System.Xaml.XamlServices.Load() method, passing in the reader returned by the OpenText method.
With the service loaded, the code opens an endpoint and listens to incoming requests through that endpoint:
Uri address = new Uri(
"http://localhost:8000/HelloWorldService");
WorkflowServiceHost1 host = new
WorkflowServiceHost1(service, address);
try
{
Console.WriteLine("Opening Service");
host.Open();
Console.ReadLine();
}
At this point, a service consumer can invoke the service and get the response back.
You've seen a working example of how to use the new declarative WCF services feature introduced with .NET 4.0. As you can see, declarative WCF services provide you with an easy-to-use, configuration-based services model, which is both flexible and extensible. It also opens up a window of opportunities for innovative use of WCF services in your .NET solutions.