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.
Service Request/Response
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.
- [ServiceContract]
- public interface IInventoryService
- {
- [OperationContract]
- public CreateProductResponse CreateProduct(CreateProductRequest request);
- }
- [DataContract]
- public class CreateProductRequest
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public decimal Price { get; set; }
- }
- [DataContract]
- public class CreateProductResponse
- {
- [DataMember]
- public int NewProductId { get; set; }
- }
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.
- [Serializable]
- public class OperationResult
- {
- public string Key { get; set; }
- public string Message { get; set; }
- }
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:
- public interface IOperationResultResponse
- {
- public void AddResult(string key, string message);
- public IList<OperationResult> Results { get; set; }
- }
- [DataContract]
- public class OperationResultResponse : IOperationResultResponse
- {
- private void initResults()
- {
- this.Results = new List<OperationResult>();
- }
- public IList<OperationResult> Results { get; set; }
- public void AddResult(string key, string message)
- {
- if (this.Results == null)
- initResults();
- this.Results.Add(new OperationResult { Key = key, Message = message });
- }
- public OperationResultResponse()
- {
- initResults();
- }
- }
And then, for all (or some, if not applicable) of your response simply inherit from the OperationResultResponse base class.
- [DataContract]
- public class CreateProductResponse : OperationResultResponse
- {
- [DataMember]
- public int NewProductId { get; set; }
- }
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:
- public class OperationResultParameterInspector : IParameterInspector
- {
- private IContainer _container;
- public OperationResultParameterInspector(IContainer container)
- {
- _container = container;
- }
- public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
- {
- // Step 1: Get UoW
- var uow = _container.GetInstance<IUnitOfWork>();
- // Step 2: Check for IOperationResult
- var opResultResponse = returnValue as IOperationResultResponse;
- if (opResultResponse != null)
- {
- // Step 3: Interrogate Results for errors
- if (opResultResponse.Results.Count > 0)
- {
- // Step 4: Rollback our UoW before sending response
- uow.Rollback();
- }
- }
- else
- {
- // Step 5: If we're still here, commit and dispose
- uow.Commit();
- }
- uow.Dispose();
- }
- public object BeforeCall(string operationName, object[] inputs)
- {
- // No implementation
- return null;
- }
- }
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.
- public class StructureMapServiceBehavior : IServiceBehavior
- {
- private IContainer _container;
- public StructureMapServiceBehavior(IContainer container)
- {
- _container = container;
- }
- public void Validate(ServiceDescription serviceDescription,
- ServiceHostBase serviceHostBase) { /* No implementation */ }
- public void AddBindingParameters(ServiceDescription serviceDescription,
- ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints,
- BindingParameterCollection bindingParameters) { /* No implementation */ }
- public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
- {
- foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
- {
- var cd = cdb as ChannelDispatcher;
- if (cd != null)
- {
- foreach (EndpointDispatcher ed in cd.Endpoints)
- {
- // Not shown: Add InstanceContextInitializers, IDispatchMessageInspectors, ICallContextInitializers, etc.
- foreach (DispatchOperation op in ed.DispatchRuntime.Operations)
- {
- // Add custom IParameterInspectors
- foreach (var pi in _container.GetAllInstances<IParameterInspector>())
- {
- op.ParameterInspectors.Add(pi);
- }
- }
- }
- }
- // Not shown: Add IErrorHandlers
- }
- }
- }
And of course, we add the mapping between IParameterInspector and our custom OperationResultParameterInspector in the traditional StructureMap way:
- public class ServicesRegistry : StructureMap.Configuration.DSL.Registry
- {
- public ServicesRegistry()
- {
- // Not shown: wiring up all other WCF extensions
- For<IParameterInspector>().Add<OperationResultParameterInspector>();
- }
- }
Conclusion
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.