Yeonho
Yeonho

Reputation: 3623

WCF: how to choose which type an interface will be serialize into?

When using WCF, how can you choose which type an interface will be serialized into? for example, the CarA type is used in the server, and they are sent to client over WCF as ICars, and the client should receive them as CarBs.

public interface ICar
{
   int Size { get; set; }
   int Price { get; set; }
}

public class CarA : ICar
{
   //ICar implementations...
}

public class CarB : ICar
{
   //ICar implementations...
}

[ServiceContract]
public interface ICarManager
{
   [OperationContract]
   ICar GetMyCar(int userID);
}

Upvotes: 0

Views: 117

Answers (3)

tom redfern
tom redfern

Reputation: 31780

"which type an interface will be serialized into" - this makes zero sense. If you send CarA's to your client the client will receive CarA's.

I think you may be asking about how to tell WCF that your service contract contains types which are derived from another type. To do this you can use ServiceKnownTypeAttribute.

UPDATE

If you want to return a type of ICar in your service operation you need to specify the concrete types which will be available on your endpoint. You do this by using the ServiceKnownTypeAttribute like so:

[ServiceKnownType(typeof(CarA))]
[ServiceKnownType(typeof(CarB))] 
[ServiceContract]
public interface ICarManager
{
   [OperationContract]
   ICar GetMyCar(int userID);
}

Upvotes: 1

Surjit Samra
Surjit Samra

Reputation: 4662

From Your server side you can only expose unique endpoint so you will expose only one endpoint as ICar and then you will choose which implementation of ICar you want to host via ServiceHost ,it can be CarA or CarB.

Now on client side you will just have a only interface as ICar and you should not be confused with which type should be serialized using your interface Icar. You will be only calling server side to get the service not the implementation.

More on ServiceHost

Use the ServiceHost class to configure and expose a service for use by client applications when you are not using Internet Information Services (IIS) or Windows Activation Services (WAS) to expose a service. Both IIS and WAS interact with a ServiceHost object on your behalf

Upvotes: 1

Turbot
Turbot

Reputation: 5233

You could look at customize reply message by implement custom extension using IDispatchMessageFormatter

try this link if help you IDispatchMessageFormatter – How to customize reply Messages on the server side

Upvotes: 1

Related Questions