Friday, May 6, 2011

Reusing Domain object contained business logic over WCF service boundries

Its really simple to do in WPF / console  .NET4. All you need is a common type library containing the business logic + data contract definition shared by both the service and the client.

Say you have the Business domain model as follows :
with a single string property that cannot be null or empty (a business rule)
Add references to this project to your client + service applications as shown:
And if you have a service which simply returns a new business domain object :
You would think that the business logic in SomeDataModel would be lost while crossing the service boundry. Not so if when adding the service reference at the client :
You click Advanced and make sure "Reuse types in referenced assemblies is checked":
So now when the client clearly disobeys a business rule defined in the domain data class as shown (by setting the property to null on an object returned from the server) :
We justly get an exception:

Enjoy!