Share via


Tip 48 – How to host a Data Service in WCF

Every wonder if you can host an Astoria Data Service in WCF?

Well turns out the answer is yes, in fact once you’ve got your references set up etc it is pretty easy.

Step 1 – Setting up your project

Here is what my working project looks like:

Project

In this example I am using VS 2010 beta 2, but this should work with VS 2008 SP1 too.

As you can see I have a Console app with an EF Entity Data Model called ProductsContext and a Data Service called ProductsCatalog.svc that exposes the ProductsContext.

Actually getting my ProductsCatalog.svc into my Console App was a little tricky – If you try Add New Item you won’t find Add Data Service because that dialog is project type sensitive, so it filters out options it considered unlikely in a Console App – I got around this by creating the Data Service in temporary Web Application project and copying it into my Console App project.

Then you need references to the appropriate assemblies System.Data.Entity (EF), System.Data.Services & System.Data.Services.Client (Astoria) and System.ServiceModel & System.ServiceModel.Web (WCF).

Now we have our project all ready to go, the next step is…

Step 2 – Exposing your Data Service

And now, courtesy of Phani, this code is all you need to expose the Data Service:

string uriBaseAddress = "https://localhost:998";
Uri[] uriArray = { new Uri(uriBaseAddress) };
Type serviceType = typeof(ProductsCatalog);

using(WebServiceHost host = new WebServiceHost(serviceType, uriArray))
{
try
{
host.Open();
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("An exception occurred:");
Console.WriteLine(ex.ToString());
host.Abort();
}
Console.WriteLine("Aborting");
Console.ReadKey();
}

As you can see we simply create a WebServiceHost for our Data Service class with the URL you want the service to be bound to. Simple.

And now you should be able to do things like this:

View

All exposed through your own little console app.

Nifty huh?

Comments

  • Anonymous
    July 21, 2010
    What are restrictions in comparison hosting the WCF Data Services in IIS?