tags:

views:

1276

answers:

2

I'm experimenting with WCF Services, and have come across a problem with passing Interfaces.

This works:

[ServiceContract]
public interface IHomeService
{
    [OperationContract]
    string GetString();
}

but this doesn't:

[ServiceContract]
public interface IHomeService
{
    [OperationContract]
    IDevice GetInterface();
}

When I try to compile the client it fails on the GetInterface method. I get an Exception saying that it can't convert Object to IDevice.

On the clientside the IHomeService class correctly implements GetString with a string as it's returntype, but the GetInterface has a returntype of object. Why isn't it IDevice?

+3  A: 

You need to tell the WCF serializer which class to use to serialize the interface

[ServiceKnownType(typeof(ConcreteDeviceType)]
Brian Genisio
I'm sorry, but I don't think I understand.Let's say I want the GetInterface method to return two different classes, SimpleDevice and AdvancedDevice, both which implements the IDevice interface.Should I then set ServiceKnownType for both the types?
Frode Lillerud
When deserializing, how does WCF know what implementing type of IHomeService to use?
Will
Yeah, I think you got it. You are telling WCF the possible types that implement the interface. You can pass any type through, just as long as WCF knows that these known types implement the interface, and are serializable.
Brian Genisio
+3  A: 

Thanks, it works when I changed it like this:

[ServiceContract]
[ServiceKnownType(typeof(PhotoCamera))]
[ServiceKnownType(typeof(TemperatureSensor))]
[ServiceKnownType(typeof(DeviceBase))]
public interface IHomeService
{
    [OperationContract]
    IDevice GetInterface();
}

I also got help from this site: http://www.thoughtshapes.com/WCF/UsingInterfacesAsParameters.htm

Frode Lillerud
Thanks for that example!
Orion Edwards