Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Interface in a WCF Service?

Tags:

c#

.net

wcf

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?

like image 379
Frode Lillerud Avatar asked Nov 21 '08 20:11

Frode Lillerud


3 Answers

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

[ServiceKnownType(typeof(ConcreteDeviceType)]
like image 130
Brian Genisio Avatar answered Oct 11 '22 14:10

Brian Genisio


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

like image 28
Frode Lillerud Avatar answered Oct 11 '22 14:10

Frode Lillerud


I initially tried to pass an interface to a WCF method but couldn't get the code to work using the answers provided on this thread. In the end I refactored my code and passed an abstract class over to the method rather than an interface. I got this to work by using the KnownType attribute on the base class e.g.

[DataContract]
[KnownType(typeof(LoadTypeData))]
[KnownType(typeof(PlanReviewStatusData))]
public abstract class RefEntityData : EntityData, IRefEntityData
like image 45
Myles J Avatar answered Oct 11 '22 13:10

Myles J