Monthly Archives: February 2011

WCF Data Services vs Web Deployment Projects

If you have an .svc file that acts as a WCF Data Services (OData) endpoint in a Web Site project, you may encounter the following error message when you try to precompile the site with Web Deployment Projects:

Exception type: System.ServiceModel.ServiceActivationException    

Exception message: The service ‘/MyService.svc’ cannot be activated due to an exception during compilation. 

The exception message is: Could not load file or assembly ‘App_global.asax, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. The system cannot find the file specified.

Inner exception type: System.IO.FileNotFoundException    

Sounds weird, but you will be surprised how elegant the solution is: let’s get rid of the whole .svc file and use ASP.NET routing!

Go to the global.asax file and register a new route:

RouteTable.Routes.Add( "MyService",
  new ServiceRoute( "MyService", 
                    new DataServiceHostFactory(), 
                    typeof( MyService ) ) );

Then implement your WCF Data Service in the MyService class:

public class MyService : DataService<MyDataModel>
{
  public static void InitializeService( DataServiceConfiguration config )
  {
    // Initialize your service here, set accesss rules, page size etc...
  }

  protected override void OnStartProcessingRequest( ProcessRequestArgs args )
  {
    base.OnStartProcessingRequest( args );

    // Set caching and custom headers here...
  }
}

The result: no more problem with Web Deployment Projects and you can have any nice virtual URL you want.