Nightmare with passing inheritance through WCF

332 Views Asked by At

We have a class in WCF Service like the following

[DataContract]
public class SampleClass:ICloneable
{ public object Clone()  { return MemberwiseClone(); } .... }

On client side where Service References added, I open the Reference in Object Browser, but it didn't pass ICloneable as an inherited Interface like "IExtensibleDataObject"

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="SampleClass",
Namespace="http://schemas.datacontract.org/2004/07/TestService")]
[System.SerializableAttribute()]
public partial class SampleClass : object, System.Runtime.Serialization.IExtensibleDataObject,
System.ComponentModel.INotifyPropertyChanged { .... }

Is there anyone know how can I pass it?

1

There are 1 best solutions below

1
Jeroen Mostert On

It can't and shouldn't be passed. Whether or not an object implements ICloneable isn't part of the service contract. The server doesn't care if the client is cloning objects, nor can it supply an implementation for the clone operation.

If you want your objects to be cloneable, you'll have to supply an implementation on the client side -- note that the class is partial, so you can simply create a new file that reads:

public partial class SampleClass : ICloneable {
    public object Clone() { 
        return MemberwiseClone();
    }
}

Of course, if you have to do this for all generated types, it could be a pain. If you are writing the service as well (or have access to the source) and that already contains the correct Clone implementations, you can use the same classes in both client and server by putting them in a separate assembly. This is not completely trivial because you need to work around some stubbornness in Visual Studio; see "WCF and Shared Reference Library Between Client & Service" for more details.

Note that the MSDN says:

The ICloneable interface simply requires that your implementation of the Clone method return a copy of the current object instance. It does not specify whether the cloning operation performs a deep copy, a shallow copy, or something in between. Nor does it require all property values of the original instance to be copied to the new instance. For example, the NumberFormatInfo.Clone method performs a shallow copy of all properties except the NumberFormatInfo.IsReadOnly property; it always sets this property value to false in the cloned object. Because callers of Clone cannot depend on the method performing a predictable cloning operation, we recommend that ICloneable not be implemented in public APIs.

If you need an object to be cloneable, you can still implement your own Clone method (and use MemberwiseClone if this is appropriate) but there is probably no good reason to use ICloneable.