【发布时间】:2009-06-01 04:33:55
【问题描述】:
虽然我正在尝试学习 WCF,而且它看起来很简单,但我遇到了一个奇怪的情况……至少在我看来这很奇怪。
为什么 ServiceHost ctor 采用具体类,而 AddServiceEndpoint 采用接口,反之则不然?从 OOP 的角度来看,后者似乎更合乎逻辑。
考虑以下几点:
[ServiceContract]
interface IVocalAnimal
{
[OperationContract]
string MakeSound();
}
...
public class Dog : IVocalAnimal
{
public string MakeSound()
{
return("Woof!");
}
}
...
public class Cat : IVocalAnimal
{
public string MakeSound()
{
return("Meeooow!");
}
}
所以现在我们想要创建一个“AnimalSound”服务,您可以通过 /AnimalSoundService/Dog 或 /AnimalSoundService/Cat 连接它以获取狗或猫的声音
...
Uri baseAddress = new Uri("net.pipe://localhost/AnimalSoundService");
ServiceHost serviceHost = new ServiceHost(typeof(IVocalAnimal), baseAddress);
serviceHost.AddServiceEndpoint(typeof(Dog), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), "Dog");
serviceHost.AddServiceEndpoint(typeof(Cat), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), "Cat");
...
但是上面的代码由于某些我不太明白的原因无法编译,ServiceHost ctor 想要具体的类(所以是 Dog 或 Cat),而 EndPoint 想要接口。
那么为什么不是反之亦然,因为在我看来,更细粒度的端点支持特定的实现更自然(因此您可以针对每个端点地址命中合同的特定实现),而更通用的 ServiceHost 应该是接受接口的那个吗?
顺便说一句,我不是迂腐。我只是诚实地试图理解,因为我确信是我在这里错过了一些东西。
【问题讨论】:
标签: .net wcf servicehost