WCF: using Interfaces in Operation Contracts

WCF (Windows Communication Foundation) is a great think. If you ever though supplying and consuming web-services with .Net 1.1 & .Net 2.0 was easy – think again! WCF goes a long way to even reduce the burden of this process!

OK, so you’re all excited about using WCF and setup your service-contract by defining an interface like this:

[ServiceContract]
public interface IReviewService
{
[OperationContract(IsOneWay=true)]
void InitiateReview(IReviewTrigger reviewTrigger, IDocument reviewDocument);
}

As you can see, I used interfaces as ther parameters for my operation-contract. Within the application I’ve a concrete implementation of the IReviewTrigger as well as the IDocument interfaces, So now you go ahead and consume your service in an application like this:

ChannelFactory<IReviewService> factory = new
ChannelFactory<IReviewService>("WorkflowDmsReviewServiceEndPoint");
IReviewService myService = factory.CreateChannel();
ReviewTrigger myTrigger = new ReviewTrigger();
Document myDocument = new Document();
myService.InitiateReview(myTrigger, myDocument);

But this is a booboo. You will get an exception from the service-host, that an object of type ReviewTrigger was not expected. Well, what should I say – the contract defined IReviewTrigger instead of ReviewTrigger. I would consider this to be a shortcomming of WCF … but who is asking me!!

Well, after struggeling with this for quite some time (and being stubborn not to use the concrete class in my operation-contract!) I found a solution. Aaron Skonnard blogged about using a NetDataContractSerializer instead of the built-in serializer … and all over sudden this works!!

Follow-Up: I finally did give up on passing complex types (objects) to operation contracts; instead I’m only passing the primary key of my object to the operation contract. This is reducing the overall overhead and eliminates the necessarity of the NetDataContractSerializer. I just read my Trigger and Document from the above example from my data-layer instead.

Leave a Comment.