How to Self hosting WCF Data Service

Posted by & filed under .Net, .Net 4.0, WCF.

WCF Data Services (formerly known as “ADO.NET Data Services”) is a component of the .NET Framework that enables you to create services that use the Open Data Protocol (OData) to expose and consume data over the Web or intranet by using the semantics of representational state transfer (REST). OData exposes data as resources that are addressable by URIs. Data is accessed and changed by using standard HTTP verbs of GET, PUT, POST, and DELETE. OData uses the entity-relationship conventions of the Entity Data Model to expose resources as sets of entities that are related by associations. – From MSDN. Last few days I got chance to explore WCF DataServices, but most of the code I found was using IIS for hosting. Here is some sample code which helps to host OData using self hosting. I am using a Console Application to host the WCF Data Service.

class Program
{
    static void Main(string[] args)
    {
        var baseAddress = new Uri("http://localhost:8080/");
        var host = new DataServiceHost(typeof(DataContextService),
            new[] { baseAddress });
        host.Open();
        Console.WriteLine("Service started. Press  to exit");
        Console.WriteLine("Listening in following endpoints");
        host.Description.Endpoints.
            ToList().ForEach(endpoint =>
                Console.WriteLine(endpoint.Address));
        Console.ReadKey();
        host.Close();
    }
}

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DataContextService : DataService
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.DataServiceBehavior.MaxProtocolVersion =
            DataServiceProtocolVersion.V2;
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        config.UseVerboseErrors = true;
    }
}

This code requires following references

  • System.Data.Services
  • System.Data.Services.Client
  • System.ServiceModel
  • System.ServiceModel.Web

Here is my screen shot of console application.

Console application - Self hosting WCF Data service

Console application - Self hosting WCF Data service

And here is the sample output while navigating to the url using IE.

Accessing self hosted WCF Data service using IE

Accessing self hosted WCF Data service using IE

You need to turn off the Feed read view to see this output in IE.

You need to run the Application as Administrator, otherwise you may not able to create the host instance.

Next post(s) I will try to cover accessing and updating data from client side.

Leave a Reply

CAPTCHA Image
*