ServiceStack the way I like it
Over the last month we’ve started using ServiceStack for a couple of our api endpoints. Here’s a breakdown of how I configured ServiceStack to work the way I like it. Hopefully you’ll find this useful.
##Overriding the defaults
Some of the defaults for ServiceStack are in my opinion not well suited to writing an api. This is probably down to the frameworks desire to be a complete web framework. Here’s our current default implementation of AppHost:
For me, the biggest annoyance was trying to find the DefaultContentType setting. I found some of the settings unintuitive to find, but it’s not like you have to do it very often!
##Timing requests with StatsD
As you can see, we’ve added a StatsD feature which was very easy to add. It basically times how long each request took and logs it to statsD. Here’s how we did it:
It would have been nicer if we could wrap the request handler but that kind of pipeline is foreign to the framework and as such you need to subscribe to the begin and end messages. There’s probably a better way of recording the time spent but hey ho it works for us.
One of my biggest bugbears with ServiceStack was the insistence on a separate request and response object, the presence of a special property and that you follow a naming convention all in the name of sending error and validation messages back to the client. It’s explained at length on the wiki and Demis was good enough to answer our question.
##RestServiceBase
The simple RestServiceBase that comes with provides an easy way of getting started, but there aren’t many hooks you can use to manipulate how it works. It would be nice if you could inject your own error response creator. We ended up inheriting from RestServiceBase and overriding how it works:
We basically chopped out the bits we’re not using and changed the thing that creates the Error Response: This allows us to respond with an error no matter what the type is for the request or what response you are going to send back. It provides us with extra flexibility above what is provided out of the box. In a nutshell, if there’s an exception in the code we will always get a stack trace in the response if debug is on.
##Validation
We had the same issue with the validation feature; if you don’t follow the convention you don’t get anything in the response body. So we followed the same practice and copied the ValidationFeature and tweaked it how we wanted it.
[Read More]