为什么.NET WCF服务所需要的接口所需要、接口、NET、WCF

2023-09-03 00:49:29 作者:江挽川.

不像ASMX实施WCF需要为你实现它的界面。我不太明白,设计背后的原因。接口为2类之间的合同......有了这样说,你经常有satisfry到相同的接口,但正在实施不同的2 WCF服务?

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?

另一个意见,在MSDN强烈建议要做到这一点:

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.
       }
   } 

你怎么把接口的优势与WCF?

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

推荐答案

没有,WCF的不要求你有一个接口,并实现它。

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.

如果你愿意,你可以把你的 [的ServiceContract] 上有许多 [OperationContract的] 服务方法 - 没有什么这样做阻止你。

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.

但同样:它的普遍接受和preached使用一个接口来分离出实际的合同作为一个接口(这样你就可以如嘲笑它测试等)的最佳实践

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.).