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 KnownType
attribute; if you're going to be passing back various implementations of IMyObject
I'd recommend this, otherwise you'll have to change the return type to MyObject
.
Additional Notes on Serialization The following rules also apply to types supported by the Data Contract Serializer:
Generic types are fully supported by the data contract serializer.
Nullable types are fully supported by the data contract serializer.
Interface types are treated either as Object or, in the case of collection interfaces, as collection types.
.....
see full MSDN Additional Notes on Serialization
EDIT:
I guess you are talking about Client Activated Object. To learn more about that see the following post Returning an interface from a WCF service You see you can only send data through serialization in WCF but no implementation. The other way arround your problem is using instancing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With