Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance of contracts in WCF

I have several WCF services in a test harness that have some similar functionality, like start/stop/clean parts of distributed system under test. I cannot use a universal contract to do that - each part of the distributed system has different steps for those operations.

I was thinking to define a base interface and derive the current WCF interfaces from them.

For Example:

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

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

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

What I have right now is those start/stop/clean operations defined in each child interface.

Q Shall I extract similar functionality into the base interface or are there any other solutions? Will I have any problems with the inheritance of contracts in WCF?

like image 367
oleksii Avatar asked Aug 05 '11 11:08

oleksii


1 Answers

Service contract interfaces can derive from each other, enabling you to define a hierarchy of contracts. However, the ServiceContract attribute is not inheritable:

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

Consequently, every level in the interface hierarchy must explicitly have the Service Contract attribute.

Service-side contract hierarchy:

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

When it comes to implementing a contract hierarchy, a single service class can implement the entire hierarchy, just as with classic C# programming:

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

The host can expose a single endpoint for the bottommost interface in the hierarchy:

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

You have not worry about contract hierarchy.
Inspired by Juval Lowy WCF book

like image 132
croisharp Avatar answered Oct 10 '22 18:10

croisharp