I want to have a function on my WCF service with its return type as an interface, but when I call it from a client I receive a System.Object, not the class that implements the interface which the service sent.
Here is some sample code:
[ServiceContract]
public interface IService
{
[OperationContract]
string SayHello();
[OperationContract]
IMyObject GetMyObject();
}
public interface IMyObject
{
int Add(int i, int j);
}
[DataContract]
public class MyObject : IMyObject
{
public int Add(int i, int j)
{
return i + j;
}
}
In the implementation of this service I have:
public class LinqService : IService
{
public string SayHello()
{
return "Hello";
}
public IMyObject GetMyObject()
{
return new MyObject();
}
}
SayHello() works well, but GetMyObject() returns a System.Object. How can change this code so that GetMyObject() returns an object which implements IMyObject?
Edit 1
Changed the code as follow:
using System.Runtime.Serialization;
using System.ServiceModel;
[ServiceContract]
public interface IService
{
[OperationContract]
string SayHello();
[OperationContract]
IMyObject GetMyObject();
}
[ServiceKnownType(typeof(MyObject))]
public interface IMyObject
{
[OperationContract]
int Add(int i, int j);
}
[DataContract]
public class MyObject:IMyObject
{
public int Add(int i, int j)
{
return i + j;
}
}
But no success!
All WCF contract argument and return types have to be serializable; interfaces aren’t. This question explores the same issue with an answer revolving around the
KnownTypeattribute; if you’re going to be passing back various implementations ofIMyObjectI’d recommend this, otherwise you’ll have to change the return type toMyObject.