C# – WCF Service Reference generates its own contract interface, won’t reuse mine

creferencereusabilitywcf

My first question so hope it is suitable:

Shared interface assembly – I have a 'shared' assembly which has an interface, let's call it IDocRepository. It's marked with [ServiceContract] and there are several [OperationContract]-marked methods.

WCF implementation assemblies – I have two WCF service projects, each referencing the shared assembly, each implementing that interface as a WCF service.

Consumer assembly – Finally, I have a 'client' project, also referencing the shared assembly, with a reference to each of the two WCF services.

However, the service references generated in the consumer assembly derive from an auto-generated version of the interface:

public partial class ExampleClient : System.ServiceModel.ClientBase<SomeNamespace.ExampleSvcRef.IDocRepository>, SomeNamespace.ExampleSvcRef.IDocRepository {

What I expected
I would have hoped that both references would instead automatically inherit the interface I defined, that the consumer/client assembly is also referencing. Kind of like the re-use of classes that it provides for parameter and return types, but for the service interface.

Why
So that I can create an instance of either service reference proxy and cast it to my interface type.

So I could modify the generated code by hand each time, but there should be better way…?

(edit: I do have 'Reuse types in referenced assemblies' and 'Reuse types in all referenced assemblies' options selected for both service references)

Best Answer

"Reuse types in referenced assemblies" only allows you to reuse Data Contracts, not Service Contracts. If you want to share Service Contracts, you don't need to use "Add Service Reference" at all. You can just use ChannelFactory directly.

// Supply the binding and address in code
Binding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress("http://tempuri.org/address");
IServiceContract channel = ChannelFactory<IServiceContract>.CreateChannel(binding, address);

// Or read them from the config file
ChannelFactory<IServiceContract> channelFactory = new ChannelFactory<IServiceContract>();
IServiceContract channel = channelFactory.CreateChannel();

The channel object will also implement ICommunicationObject, so you can cast it if you need to call methods like Open() or Close().

Related Topic