This question came up the other night at the June NEBytes meeting after a presentation by Iain Angus (Black Marble) on WCF Data Services – can you host a WCF Data Service outside of IIS, inside a console application for example?
Since WCF Data Services are based upon the normal WCF architecture, you can self-host them just like any other WCF Service using a DataServiceHost. As a quick example, try this:
1. Create an entity
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
2. Create a custom data context to return some data
public class ExampleDataContext
{
public IQueryable People
{
get
{
return new List()
{
new Person() { ID = 1, Name = "Steve"},
new Person() { ID = 2, Name = "Dave"}
}.AsQueryable();
}
}
}
3. Create a class which inherits from DataService<T> and specify your custom context. Also implement the static InitializeService() method and set up your access rules. This is the stuff that would normall be in your .svc code-behind in the IIS-hosted version:
public class PersonDataService : DataService
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
}
}
4. Finally, in your startup code create an instance of a DataServiceHost, specifying the typeof DataService and the Uri to host on. Open the host and wait for a key-press to close it again:
DataServiceHost host = new DataServiceHost(typeof(PersonDataService), new Uri [] { new Uri("http://localhost:999")});
try
{
host.Open();
Console.WriteLine("Host is running; press a key to stop");
Console.ReadKey();
host.Close();
}
catch (Exception)
{
host.Abort();
throw;
}
Using this example, you can now browse to http://localhost:999 in your browser and retrieve your data. You can also create a client proxy against this service at the same Uri just as normal.
You can read more information on hosting WCF Data Services in IIS or otherwise on MSDN.