views:

504

answers:

2

I have some object classes that use inheritance. It seems that I can only get access to the objects that are directly used by a service. Let me show you what I am trying to accomplish:

[DataContract]
public class Object1
{
   [DataMember]
   int Id {get; set;}
}

[DataContract]
public class object2: Object1
{
   [DataMember]
   string Name {get; set;}
}

[DataContract]
public class object3 
{
    [DataMember]
    int SomeNumber {get; set;}
}

The Service:

public int GetId(object2 obj)
{
    return GetTheId(object2.Name);
}

Now since I am using object2 in the service, object1 gets serialized too. Howerver, I may want to have object3 exposed for some reason. It may be a derived class that I have to pass so that its type can be determined later for another process. I do not see this object getting serialized. I assumed that whenever you set the DataContract / DataMember those objects would get serialized. It does make sense not to expose something that is not begin used, becuase I can see an issue with exposing items you may not need. What is the best way to expose objects that are not directly used by a service? Thanks

Daniel

A: 

I believe you answered your own question. If the members are not being used by the service, then you shouldn't be exposing them. It is always better to expose the minimal set of data required by the service, as it will generally increase maintainability of the service.

casperOne
Exactly, but what is the best way to expose an object that isn't directly used?
DDiVita
Don't do it is the best way. The only thing from the server that the client should know about is objects used by service operations.
John Saunders
This ignores the fact that inheritance is a reality in these situations. This is a reality for both contracts designed in code and those designed in XML schema - you have to define "inherited" types so that the client can have a definition for that type.
Anderson Imes
+1  A: 

You should decorate object2 (peculiar name for a class :)) with the KnownType attribute:

[DataContract]
[KnownType(typeof(object3))]
public class object2 
{
}

Assuming you mean object3 is a subclass of object2:

public class object3: object2
{
}
veggerby
I totally forgot about that attribute!!! Thanks. That is what I needed in htis situation. Thanks!!!!!
DDiVita
You can also decorate your service contract with [ServiceKnownType]. :)
Anderson Imes