Applying ServiceContract and OperationContract on existing interfaces

.net, c#, wcf

Solution

You could simply extend the interface with a service-warpper type interface, i.e.:

public interface IMyCode
{
    string GetResult();
}

[ServiceContract]
public interface IMyCodeService : IMyCode
{
    [OperationContract]
    string GetResult();
}

C# allows interface inheritance, and the compiler will spit out a warning that `IMyCodeService.GetResult` requires new because it hides the `IMyCode.GetResult` method, but not appending `new` will not break the implementation, as an example:

class Program
{
    static void Main(string[] args)
    {
        MyCodeService service = new MyCodeService();
        IMyCodeService serviceContract = (IMyCodeService)service;
        IMyCode codeContract = (IMyCode)service;

        service.GetResult();
        serviceContract.GetResult();
        codeContract.GetResult();

        Console.ReadKey();
    }
}

public interface IMyCode
{
    void GetResult();
}

public interface IMyCodeService : IMyCode
{
    void GetResult();
}

public class MyCodeService : IMyCodeService
{
    public void GetResult()
    {
        Console.Write("I am here");
    }
}

That way, you can provide a service contract based on your existing interface without changing your existing code.

If you share your contract assembly instead of using WCF to generate a proxy for you, you can even pass your service contract in places where you'd accept your existing interface, because the service interface inherits from it.

Problem

I have some existing interfaces that are used over all over system. Now I want to use one of the interfaces to be as service contract. But the problem is that I need to add `[ServiceContract]` and `[OperationContract]` attributes on existing interfaces and they will contaminate the rest of the code . Any solution to this problem with out duplicating the interfaces? Applying the attributes on the concrete implementation ? is that a good practice ? Thanks

Original source