Reputation: 8748
I'm working with a 3rd party API whose objects I am exposing through a web service. Unfortunately the API has some quirks, including throwing exceptions when trying to access some properties if the object's ID field is 0.
So I'm creating a valid instance of the object on the server and pushing it through a WCF service to the client. The problem occurs when the client receives the object. It seems that for whatever reason, the service inspects each of the properties of the object before it populates them on the client. So the objects are throwing exceptions when the client receives them but before I'm able to do anything with them. Here's some quick example code to demonstrate what is happening.
public class ExposedClass {
public int Id { get; set; }
List<OtherClass> _other;
public List<OtherClass> Other {
get {
if (Id == 0) throw new Exception("Can't access field 'other' if object not initialized");
return _other;
}
}
}
In the service:
[ServiceContract]
public MyService {
[OperationContract]
public ExposedClass GetThing() {
ExposedClass c = new ExposedClass();
c.Initialize(); // makes the Id field valid
return c;
}
}
And the client:
[TestMethod]
public void GetThingFromService {
var svcClient = new MyClient();
var c = svc.GetThing(); // exception thrown here on client
Assert.IsNotNull(c);
}
Any ideas?
Upvotes: 0
Views: 129
Reputation: 20820
Usually a DataContract class should not contain any programming logic. It is used as a sort of container to store information which is passed to the client.
My approach would be to copy the information I need from the 3rd party object onto a custom DTO (Data Transfer Object) before sending it down the network.
Are the 3rd party classes actually required at the client end? If possible it would be a good idea to discard the 3rd party objects at the server, thus layering and insulating your users from buggy code which you have no control over.
Upvotes: 4
Reputation: 88044
There are two possibilities:
An object should never depend on the order of fields being assigned for this exact reason.
Upvotes: 1