Exitos
Exitos

Reputation: 29720

How to I expose a type as a different name in WCF?

I have a class

class Video
{
   public string name;
   public string description;
}

And because its exposed through a WCF interface I want to rename it (the business object has now been modified to encapsulate audio and images as well as video).

So my solution was to write another class that inherits from it:

class MediaItem : Video
{
}

We have a 'factory' like class that gets a video from the the database.

public Video GetVideo(int videoId)
{
}

However when I call the following:

MediaItem itemToReturn = (MediaItem)contentManagerforPage.GetVideo(mediaId);

I get the error:

Unable to cast object of type 'Video' to type 'MediaItem'.

I understand that I cant do this (cast a baseclass to a subclass). So what is the solution?

I cant expose the class name 'Video' through WCF I need to expose MediaItem. Is there any OO approach to this problem (using an interface perhaps)?

If not can I rename the object in WCF attributes?

Upvotes: 1

Views: 165

Answers (3)

CharithJ
CharithJ

Reputation: 47510

The default name of a data contract for a given type is the name of that type. To override the default, set the Name property of the DataContractAttribute to an alternative name.

[DataContract(Name = "MyMediaItem")]

See here and here for more details.

Upvotes: 0

RoelF
RoelF

Reputation: 7573

Or you could make Video inherit from MediaItem and make MediaItem abstract. Then use the KnownType attribute on the class definition to specify the implementations.

see here for more info

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151586

Video should inherit from MediaItem, not the other way round.

You could decorate the class with [DataContract(Name="YourName")] to supply an other name than you're using in code.

Upvotes: 6

Related Questions