为什么 .net WCF 服务需要接口

Why does .net WCF Service require the Interface(为什么 .net WCF 服务需要接口)
本文介绍了为什么 .net WCF 服务需要接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与 asmx 实现不同,wcf 需要您实现它的接口.我不太明白这种设计背后的原因.接口是 2 个类之间的契约...话虽如此,您多久有 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.

但同样:使用接口将实际合约分离为接口是普遍接受和宣扬的最佳实践(因此您可以模拟它以进行测试等).

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

这篇关于为什么 .net WCF 服务需要接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)