【问题标题】:Contract Namespace — No Conflict and Why?合约命名空间——没有冲突,为什么?
【发布时间】:2017-09-20 16:29:38
【问题描述】:

我正在学习 WCF,作为学习的一部分,我发现合同的命名空间应该匹配。我编写了一个合同类(客户端和主机都有自己的副本)并使它们的命名空间不匹配,但我的代码仍然有效。我已经为我的合同和主机类以及客户如何调用合同提供了代码。有人可以告诉我哪里错了吗?

客户端合同类:

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();
    }

【问题讨论】:

    标签: c# wcf namespaces


    【解决方案1】:

    ServiceContracts 或 DataContracts 中的Namespace 通常为used for versioning,因为它们允许两个同名对象存在于不同的命名空间中。

    但是,您似乎还没有为您的服务定义命名空间。

    定义一个命名空间就像:

    [ServiceContract (Namespace="http://yourcompany.com/MyService/V1")]
    public interface IMessageContract
    {
        ...
    }
    

    如果您稍后引入具有新实现的新版本服务并将其放在单独的命名空间中,例如:

    [ServiceContract (Namespace="http://yourcompany.com/MyService/V2")]
        public interface IMessageContract
        {
            ...
        }
    

    然后您可以将这两个服务分开,让旧客户端调用版本 1 和新客户端调用版本 2

    【讨论】:

    • 我正在学习 Miguel Castro 关于 Pluralsight 的 WCF 课程,他建议使用命名空间属性的原因,就像您建议在不共享合同并让主机和客户端使用自己的合同时停止命名空间冲突一样。
    猜你喜欢
    • 2010-09-20
    • 1970-01-01
    • 2011-07-01
    • 2013-01-26
    • 2010-11-15
    • 2012-12-18
    • 2012-02-06
    • 1970-01-01
    相关资源
    最近更新 更多