Sunday 8 March 2015

Why to Program WCF Service Contract as Interface

If you have not dug deeper or not paid much attention, you won't even be aware that you can program a WCF service contract to a concrete type also, not just to an interface.
Microsoft has provided a lot of ease to the developer but in some senses it has made the developer a little lame also. Providing the ease in the sense that, fro example, if you create a WCF service the visual studio will render a default template to build up your service. Then you do not bother much about why it has generated a specific code? You may sometimes even not take that as an standard guideline but the rule and you start following that up, and that makes you lame as you loose the deeper understanding of the subject.
The same happened with me also until one day it struck to my mind that why I am using this interface as a service contact. I just removed that interface and made the service class as service contract and defined methods inside it as operation contracts, and the service worked fine.
Now I started thinking like why then we expose this through an interface? what are the advantages?
So, here I get it:

  • First of all, as a thumb rule, if we want to follow best design practices we should always program to interface not to implementation. It gives a lot of flexibility and decoupling of the code.
  • Secondly, If a service is exposed through interface, we can make any changes to our implementation without breaking the client, even the name of the service class can be changed.
  • Another advantage can be like, suppose we have a service MyService that exposes O1, O2 nad O3 operation contracts to a client through IMyService1 contract. Now a situation comes where another client comes and asks for the service but wants only O1 and O2 operations and we as a service provider do not want to provide him O3 then it is very easy to do this if we have exposed our service with the interface. What we can do is simply create another contract as IMyService2 that exposes only O1 and O2 operation contracts an expose the service with this contract to this client. Now consider another situation where a client want one more operation contract O4 along with the three, what we can do here create another service contract IMyService3 which exposes only O4. Now the service can be exposed to this client with service contracts IMyService1 and IMyService3. So the crux here is that we can accomplish these changes otherwise also but not with such an ease and minimal changes.


I hope I could explain the idea. If anyone wants to add something to it, then it would be great and more helpful to the readers.


No comments:

Post a Comment