Self-Hosting a WCF Data Service

I’ve seen several customers looking for an example of how to directly host a WCF Data Service in a WCF application rather than using traditional ASP.NET hosting. While we discuss self-hosting WCF services in the topic Hosting the Data Service (WCF Data Services), there is current no example of this kind of hosting. I do have a working code example that I have shared out on the forums, but I’m not sure that I want to put it in the core documentation because a) it’s overly simplistic, running in a console application, and b) it doesn’t address crucial issues of security and reliability, which is one of the main reasons to use ASP.NET and IIS for hosting. In fact, whenever you self host a data service (either directly in WCF or in some other application), you need to make sure to consider the twin security requirements of authentication and authorization (unless it’s OK to run with wide-open access to your data).

Anyway, here’s sample code for a Northwind-based data service that is self-hosted in a console application:

using System;
using System.Data.Services;

namespace CustomHostedDataService
{
// Self-hosted data service definition based on the Northwind
// and using the Entity Framework provider.
public class ConsoleService : DataService<NorthwindEntities>
{
public static void InitializeService(
IDataServiceConfiguration config)
{
// Provide read-only access to all entries and feeds.
config.SetEntitySetAccessRule(
"*", EntitySetRights.AllRead);
}
}

    class Program
{
static void Main(string[] args)
{
Type serviceType = typeof(ConsoleService);
Uri baseAddress = new Uri("https://localhost:6000/");
            Uri[] baseAddresses = new Uri[] { baseAddress };

            // Create a new hosting instance for the Northwind
// data service at the specified address.
DataServiceHost host = new DataServiceHost(
serviceType,
baseAddresses);
host.Open();

            // Keep the data service host open while the console is open.
Console.WriteLine(
"Navigate to the following URI to see the service.");
Console.WriteLine(baseAddress);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();

            // Close the host.
host.Close();
}
}
}

Note: You need to run the application as an administrator to be able to create the host instance.

If you think that this example should be added to the hosting topic, please leave a comment.

Cheers,

Glenn Gailey
WCF Data Services
User Education