【问题标题】:Inheritance of contracts in WCFWCF中合同的继承
【发布时间】:2011-10-20 18:57:35
【问题描述】:

我在一个测试工具中有几个 WCF 服务,它们具有一些类似的功能,例如被测分布式系统的启动/停止/清理部分。我不能使用通用合约来做到这一点 - 分布式系统的每个部分对这些操作都有不同的步骤。

我正在考虑定义一个基本接口并从中派生当前的 WCF 接口。

例如:

interface Base
{
    void BaseFoo();
    void BaseBar();
    ...
}

interface Child1:Base
{
    void ChildOperation1();
    ...
}

interface Child2:Base
{
    void ChildOperation2();
    ...
}

我现在拥有的是在每个子界面中定义的启动/停止/清理操作。

Q我应该将类似的功能提取到基本界面中还是有其他解决方案?在 WCF 中继承合同会有什么问题吗?

【问题讨论】:

    标签: .net wcf inheritance interface


    【解决方案1】:

    服务契约接口可以相互派生,使您能够定义层次结构 的合同。但是,ServiceContract attribute is not inheritable

    [AttributeUsage(Inherited = false,...)]
    public sealed class ServiceContractAttribute : Attribute
    {...}
    

    因此,接口层次结构中的每一层都必须明确地具有服务 合约属性。

    服务端合约层次结构:

    [ServiceContract]
    interface ISimpleCalculator
    {
        [OperationContract]
        int Add(int arg1,int arg2);
    }
    [ServiceContract]
    interface IScientificCalculator : ISimpleCalculator
    {
        [OperationContract]
        int Multiply(int arg1,int arg2);
    }
    

    在实现合同层次结构时,单个服务类可以实现 整个层次结构,就像经典的 C# 编程一样:

    class MyCalculator : IScientificCalculator
    {
        public int Add(int arg1,int arg2)
        {
            return arg1 + arg2;
        }
        public int Multiply(int arg1,int arg2)
        {
            return arg1 * arg2;
        }
    }
    

    主机可以为层次结构中最底层的接口公开一个端点:

    <service name = "MyCalculator">
        <endpoint
        address = "http://localhost:8001/MyCalculator/"
        binding = "basicHttpBinding"
        contract = "IScientificCalculator"
        />
    </service>
    

    您不必担心合同层次结构。
    灵感来自Juval Lowy WCF book

    【讨论】:

      猜你喜欢
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多