Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does .net WCF Service require the Interface

Unlike the asmx implementation the wcf requires for you to implement it's interface. I do not quite understand the reason behind that design. Interface is a contract between 2 classes...With that being said, how often do you have 2 wcf services that satisfry to the same interface but being implemented differently?

Another comment, the msdn strongly recommends to do this:

   MyService service = new MyService();

   try {

      service.DoWork();

   }
   catch(Exception) {}
   finally {
      service.Close();
   }

So let's say if I am to inject my service with using it's interface like this:

   public MyComponent : IDisposable
   {

       readonly IMyService service = null;

       public MyComponent(IMyService service) {

           this.service = service;

       }

       public DoWork() 
       {
           //some additional code.
           this.service.DoWork();

       }

       public void Dispose() 
       {
           //The Interface does not have the Close method,
           //So doing this defeats the whole purpose of polymorphysm
           (this.service as MyService).Close(); //Silly.
       }
   } 

How do you take the advantage of the interface with WCF?

like image 790
dexter Avatar asked Mar 02 '11 15:03

dexter


Video Answer


2 Answers

No, WCF does NOT require you to have an interface and implement it.

It's just generally accepted best practice to do so - but you don't have to, if you don't want to.

If you want to, you can put your [ServiceContract] on a concrete class that has a number of [OperationContract] service methods - there's nothing stopping you from doing so.

But again: it's generally accepted and preached best practice to use an interface to separate out the actual contract as an interface (so you can e.g. mock it for testing etc.).

like image 173
marc_s Avatar answered Nov 01 '22 23:11

marc_s


Actually, even MSDN concedes from time to time that the formality of interfaces may not always be "the right thing to do":

http://msdn.microsoft.com/en-us/library/ms733070.aspx

"The advantage of creating your services by applying ServiceContractAttribute and OperationContractAttribute directly to the class and the methods on the class, respectively, is speed and simplicity."

like image 24
McGuireV10 Avatar answered Nov 01 '22 21:11

McGuireV10