If you've tried to pass NHibernate objects over the wire using a webservice before, you know how painful it can be. But what about WCF? Can it ease your pain? Well, yes, of course it can. This wouldn't be a very interesting post if the answer was no.
There are three main issues that needed to be fixed: serializing circular references, passing generic list to the client (and not having them converted to arrays), and serializing NHibernate/Castle proxy objects.
Serializing circular references.
An example of a circular reference would be a User object that has a collection of Roles and each of those Role objects has a collection of User objects. In the past (with webservices) this meant you had to decorate the offending properties with [XMLIgnore] to serialize your objects. This meant that your object graph would be quite different over the wire.
Let's not dwell on the past. The DataContractSerializer can preserve your object references, but not by default. You're going to need to extend DataContractSerializerOperationBehavior as described here in an excellent article by James Kovacs. The code included with this post is built using his example.
Passing generic collections to the client.
Specifically, I’m talking about passing objects that contain collections implemented as IList<T> as is necessary to use generics with NHibernate. This was actually a two part problem. The default serialization in ASP.NET webservices (XMLSerializer) could not serialize an interface and even when casting to List<T> the client would see the collection as an array, not a generic list. In WCF, the DataContractSerializer can serialize IList<T>. Getting the client to see the collection properly requires you to generate your service proxies using the command line utility svcutil.exe (you can’t do it using the IDE in VS2005, but you will be able to in VS2008). The command will look something like this (notice the /ct switch, a shortened form of the switch /collectiontype):
svcutil /language:cs /ct:System.Collections.Generic.List`1 /out:AdministrationClient http://localhost:3796/NHBlog.WebUI/Administration.svc
Serializing NHibernate/Castle proxies.
I’m going to save this topic for a separate post. Actually, I’m still testing and getting some unexpected results that I need to quantify first. For now, download the sample code included with this post and try it for yourself.
Notes about the sample code.
If this is the first time you are running this app (it’s an extension of the sample code from my previous posts) you will need to make sure and add an initial application to the “Applications” table in the database setting the application name to “NHBlog”. This is a requirement of the custom MembershipProvider included in the sample.
This code has been used and reused and modified many times. As a result, it may have some rough edges in the presentation but the underlying framework should be solid.
09-25-2007 3:27 PM