Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose an interface in web service

Tags:

c#

interface

wcf

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!

like image 280
mans Avatar asked Mar 07 '12 12:03

mans


2 Answers

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.

like image 150
Steve Wilkes Avatar answered Oct 08 '22 03:10

Steve Wilkes


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.

like image 36
CSharpenter Avatar answered Oct 08 '22 03:10

CSharpenter