Share type between two WCF services

1.3k views Asked by At

I have two WCF services on my project. Services are sharing one type, but each service generating its own type. Is it possible to generate one class for both services?

Sample code for server side:

[DataContract]
class MyClass { /*some properties*/ } 

[ServiceContract]
public interface IService1 
{
    [OperationContract]
    MyClass GetSomeValue();
}

public class Service1 : IService1
{
   public MyClass GetSomeValue() { /*some logic*/ }
}

[ServiceContract]
public interface IService2 
{
    [OperationContract]
    MyClass GetSomeOtherValue();
}

public class Service2 : IService2
{
   public MyClass GetSomeOtherValue() { /*some logic*/ }
}

On client side two "MyClass" are generating for each service:

namespace Services.Service1Reference {
[System.SerializableAttribute()]
public partial class RSTRole : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged 
{
}

and

namespace Services.Service2Reference {
[System.SerializableAttribute()]
public partial class RSTRole : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged 
{
}
1

There are 1 answers

3
StuartLC On

This requires a few changes

  1. You'll need to reference same actual assembly used to contain the Shared Entities (DTO's) on the two services directly in the Client assembly (i.e. add this assembly as a reference the same project to which you are adding the WCF Service References). As per Dimitri's comment, it makes sense to refactor the shared entities into a small assembly just containing the DTO's, if you haven't done so already.

  2. On the client, you'll need to select Advanced when adding the service reference, and then select Reuse Types in Referenced Assemblies, as per the following:

Service reference with Shared Type