So Special - InitializeService in ADO.NET Data Services

In this post I'd like to talk a bit about the InitializeService method that ADO.NET Data Service writers should implement on their services.

Usually this would have been a virtual method that developers could override, however it was important to stress that this was meant to execute outside the context of a request, and the the initialization occurred a single time, and then "stuck" for every other request.

Now, here are a few interesting things about this method.

For one, you can't reinitialize the service once it's complete - the configuration is cached in an internal static dictionary, so it'll stay there as long as the AppDomain stays around. An AppDomain restart isn't usually a big deal if you're re-deploying the service. Configuration changes can modify the conceptual model (CSDL) provided by service.svc/$metadata, which means that different requests may see a different view of the URL space provided by the service - not a small thing. So we prefer to stay away from anything that can change what the client perceives as "static" on a per-request basis - thus the whole point for single-time initialization.

Now, the service itself doesn't spring into being initialized, so initialization actually happens when the first request is received. However from the above you can tell that it's a really, really bad idea to try and do something based on the requests that's available on the thread at that point (depending on your hosting story), so I urge folks not to do that. It's best to just use the InitializeService method to just set the configuration options that you want and leave it at that.

Another interesting point has to do with error handling. The option for error handling is set during InitializeService. If an exception is thrown while InitializeService is being called, we don't trust whatever was set on the configuration, and instead of the ADO.NET Data Service error handling kicking in, we'll let the exception bubble out. Typically the service will be running as a WCF service, which means you'll get the error page with the blue band on top (when viewed in a browser). To get detailed errors in this case, you can do something like this.

[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class YourService : DataService<YourContext>
{ ... }

I'll include the IncludeExceptionDetailInFaults warning here, and say that this is something that you only want to use for troubleshooting purposes during development - don't put this attribute in production code!

In the next post, a few more interesting tidbits that have to do with service initialization, but with a focus on the configuration object.