WCF中合同的继承

ole*_*sii 11 .net wcf inheritance interface

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

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

例如:

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

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

interface Child2:Base
{
    void ChildOperation2();
    ...
}
Run Code Online (Sandbox Code Playgroud)

我现在拥有的是每个子接口中定义的启动/停止/清理操作.

问:我应该在基本界面中提取类似的功能,还是有其他解决方案?我在WCF中继承合同会有任何问题吗?

cro*_*arp 20

服务合同接口可以相互派生,使您可以定义合同层次结构.但是,ServiceContract attribute is not inheritable:

[AttributeUsage(Inherited = false,...)]
public sealed class ServiceContractAttribute : Attribute
{...}
Run Code Online (Sandbox Code Playgroud)

因此,接口层次结构中的每个级别都必须明确具有"服务合同"属性.

服务端合同层次结构:

[ServiceContract]
interface ISimpleCalculator
{
    [OperationContract]
    int Add(int arg1,int arg2);
}
[ServiceContract]
interface IScientificCalculator : ISimpleCalculator
{
    [OperationContract]
    int Multiply(int arg1,int arg2);
}
Run Code Online (Sandbox Code Playgroud)

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

class MyCalculator : IScientificCalculator
{
    public int Add(int arg1,int arg2)
    {
        return arg1 + arg2;
    }
    public int Multiply(int arg1,int arg2)
    {
        return arg1 * arg2;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<service name = "MyCalculator">
    <endpoint
    address = "http://localhost:8001/MyCalculator/"
    binding = "basicHttpBinding"
    contract = "IScientificCalculator"
    />
</service>
Run Code Online (Sandbox Code Playgroud)

您不必担心合同层级.
灵感来自Juval Lowy WCF的书