Search code examples
c#wcf.net-4.5

Cannot have two operations in the same contract with the same name (Async & Non)


I get the following exception (Cannot have two operations in the same contract with the same name, methods ExecuteAsync and Execute) when the following service is activated.

    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        byte[] Execute(MyRequest request);

        [OperationContract]
        Task<byte[]> ExecuteAsync(MyRequest request);
    }

I guess this makes sense if you are using the svcutil.exe to create your service reference, because the task-based operations are created automatically for you. However, I don't want to add a service reference and instead just use the standard ChannelFactory to create the WCF Channel. Is there any other way this is possible without renaming the async method to something else? Or must I wrap the sync method on the client in a Task.Run?


Solution

  • Here's what I did. I have two separate contracts. One for the client and one for the server:

    namespace ServiceLibrary.Server
    {
        [ServiceContract]
        public interface IMyService
        {
            [OperationContract]
            byte[] Execute(MyRequest request);
        }
    }
    
    namespace ServiceLibrary.Client
    {
        [ServiceContract]
        public interface IMyService : Server.IMyService
        {
            [OperationContract]
            Task<byte[]> ExecuteAsync(MyRequest request);
        }
    }
    

    Because both ServiceContracts share the same name, the OperationContracts' Action and ReplyAction are the same for the async and sync methods. The client now has both the sync and async version and the server stays unmodified.