简体   繁体   中英

How to expose an interface in web service

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM