我正在学习 WCF,作为学习的一部分,我发现契约(Contract)的命名空间应该匹配。我编写了一个契约(Contract)类(客户端和主机都有自己的副本)并使它们的命名空间不匹配,但我的代码仍然有效。我已经为我的合约和宿主类以及客户端如何调用合约提供了代码。有人可以告诉我哪里错了吗?
客户合约类别:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace GeoLib.Client.Contracts
{
[ServiceContract]
public interface IMessageContract
{
[OperationContract (Name = "ShowMessage")]
void ShowMsg(string message);
}
}
主机合约类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace GeoLib.WindowsHost.Contracts
{
[ServiceContract]
public interface IMessageContract
{
[OperationContract]
void ShowMessage(string message);
}
}
客户端调用代码:
private void btnMakeCall_Click(object sender, RoutedEventArgs e)
{
ChannelFactory<IMessageContract> factory = new ChannelFactory<IMessageContract>("");
IMessageContract proxy = factory.CreateChannel();
proxy.ShowMsg(txtMessage.Text);
factory.Close();
}
最佳答案
Namespace在 ServiceContracts 或 DataContracts 通常是 used for versioning因为它们允许两个具有相同名称的对象存在于不同的命名空间中。
但是,您似乎还没有为您的服务定义命名空间。
定义一个命名空间就像:
[ServiceContract (Namespace="http://yourcompany.com/MyService/V1")]
public interface IMessageContract
{
...
}
如果您稍后引入具有新实现的服务的新版本并将其放在单独的命名空间中,例如:
[ServiceContract (Namespace="http://yourcompany.com/MyService/V2")]
public interface IMessageContract
{
...
}
那么你可以将这两个服务分开,让旧客户端调用 version1,新客户端调用 version2
关于c# - 契约(Contract)命名空间——没有冲突,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43580504/