Returning an unknown interface from a WCF Service

The Problem

There are times when creating a WCF service that you may want to return a value, whilst not knowing precisely which value; for example, a service contract such as this:

[ServiceContract]
public interface IMyService
{
    [OperationContract()]
    FunctionResult MyFunction(string parameter);
}

… and a data contact like this:

[DataContract]
public class FunctionResult
{
    private int _myData;
    [DataMember(Name="MyData")]
    public int MyData
    {
        get { return _myData; }
        set { _myData = value; }
    }
	
    // Here, I want to return a class, 
    // but it may be a number of different 
    // options that share no commonality
}

So, how?

One solution to this, right or wrong, is to create a blank interface:

interface IData { }

Then to implement it in whichever class I want to return:

public class MyClass : IData

Finally, include this in my `FunctionResult` return class:

[DataContract]
public class FunctionResult
{
    private int _myData;
    [DataMember(Name="MyData")]
    public int MyData
    {
        get { return _myData; }
        set { _myData = value; }
    }

    private IData _returnData;
    [DataMember(Name="ReturnData")]
    public IData ReturnData
    {
        get { return _returnData; }
        set { _returnData = value; }
    }
}

You do need to declare the concrete class as a `ServiceKnownType`:

[ServiceContract]
[ServiceKnownType(typeof(MyClass))]
public interface IMyService
{
    [OperationContract()]
    OperationResult MyFunction(string paramater);
}

Acknowledgements

The `ServiceKnownType` wasn’t something I had come across before – thankfully, we have StackOverflow for that kind of thing:

http://stackoverflow.com/questions/310160/passing-interface-in-a-wcf-service

Leave a Reply

Your email address will not be published. Required fields are marked *