问题描述
与 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 服务需要接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!