When I initially set off on using StructureMap as my IoC of choice on a recent ASP.NET MVC/WCF project, I didn’t realize how deep the rabbit hole actually was. Oh, the MVC part was easy. StructureMap integration in an MVC application has been demonstrated a thousand times over and is made even easier with the latest release of ASP.NET MVC 3 and NuGet. Getting StructureMap to serve up objects in a WCF application, now THAT’S a horse of a different color.
Standing on Someone Else’s Shoulders
Two blog posts helped me tremendously when attempting this:
- Jimmy Bogard’s Integrating StructureMap with WCF – lays the ground work for using a custom ServiceHostFactory in order to add customizations at WCF’s extension points.
- Andreas Öhlund's UnitOfWork in WCF using StructureMap – takes Jimmy’s post and builds on it using the Unit of Work pattern to automatically initialize, commit or rollback transactions (in my case, NHibernate session transactions) automatically in the WCF pipeline.
I highly recommend reading both posts first, in that order.
Before going any further, I need to take a moment to define the pattern I was using on the project for calling the WCF service layer. For each service operation I defined two data contracts: [OperationName]Request; and [OperationName]Response. Both of these classes are decorated with the DataContract attribute and encapsulated the parameters in both the request and response to the service. This allows the values that are passed into and returned from the service to change without breaking the service contract. Much more flexible, IMHO. Here’s an example.
Taking it a Step Further
Andreas’ example would rollback the transaction if an unhandled exception was thrown in the WCF application. This is all well and good but I didn’t like the idea of throwing exceptions from my service layer. I thought a much cleaner approach would be to return one or more OperationResult objects in the service response object if a problem occurred. An OperationResult would basically just consist of a Key/Message pair that identifies exactly what or where something went wrong (in the Key) as well as details of the error (in the Message). In most cases, this could represent validation errors bubbled up from the domain model. The Key would be the property name that was invalid and the Message would contain, well, the error message of the validation error (e.g., “Email address is in the wrong format”). But this could also include other, more generic, errors as well.
I decided to create a base class that contained a collection of OperationResult objects so that I wouldn’t have to reinvent the wheel for every Response object I created. It looks like this:
And then, for all (or some, if not applicable) of your response simply inherit from the OperationResultResponse base class.
Where the Magic Happens
OK, that was a lot of lead up to the big reveal. How do we take this service request/response object model and use it to rollback our Unit of Work (and consequently our NHibernate session transaction)? I got one, err, two, ish words for you: IParameterInspector. This is another one of WCF’s many extensibility points and, like IDispatchMessageInspector, it allows you to perform work when a request is received and before a response is sent. In our case, we want to perform the following steps before each response is sent:
- Get a reference to the Unit of Work for the current request
- Check the response object type and see if it implements IOperationResultResponse
- If the response object DOES implement IOperationResultResponse, interrogate the Results property to see if there are any errors contained therein
- If there ARE errors in the Results property, rollback the Unit of Work by calling Rollback()
- If none of the above applies, call Commit() and Dispose() on the UoW before sending the response on its way
Here’s what our IParameterInspector implementation looks like:
Why We Can’t Use BeforeSendReply
We’re still going to reuse the Andreas’ UnitOfWorkMessageInspector to create and initialize the Unit of Work in the AfterReceiveRequest but instead of committing and disposing of the UoW in the BeforeSendReply method, we’re going to rely on our parameter inspector’s AfterCall method to do the work. The reason we’re not performing the above logic in the BeforeSendReply method of IDispatchMessageInspector is because BeforeSendReply happens AFTER the response has been serialized into a Message object, making it much more difficult to interrogate the values. Believe me, I tried. AfterCall of IParameterInspector is invoked BEFORE the return value has been serialized into a Message object so you can easily just cast the return value to our IOperationResultResponse interface.
Wiring It All Up
Wiring up our IParameterInspector is just like wiring up the IDispatchMessageInspectors, IErrorHandlers, etc. Iterate through each EndPoint, get the list of IParameterInspectors (you may have more than one!) from StructureMap and append them to each DispatchOperation. Here’s what our updated StructureMapServiceBehavior class looks like. I’ve omitted the other details for brevity.
And of course, we add the mapping between IParameterInspector and our custom OperationResultParameterInspector in the traditional StructureMap way:
This really turned into an exercise in learning the various WCF extension points, what you can and cannot do at each, etc. We’ve learned though that the best place for inspecting the actual service response objects before they’re sent across the wire is in the AfterCall method of the IParameterInspector interface.