Datacontracts property getter running twice
I have a set of data contracts that act as wrappers to base classes that we wish to expose. A quick example is:
[DataMember]
public List<decimal> Points
{
get
{
return sourceObject.ListPoints();
}
private set{}
}
We have some other properties that we have to massage the data first (we are converting object graphs and need to guard against circular references).
The issue that we are seeing is that this getter will fire twice, once within the service operation, then again during serialization. This is causing two problems:
- We manually add to collections, since this is running twice the collections are filled with dupes.
- If an exception is thrown during the second run, it happens outside of the try/catch in the operation, and does not throw a fault. The ser开发者_开发知识库vice throws a cryptic timeout message, and the only way to see the error is via WCF trace logs.
You could simply "cache" the values. For example:
public class MyWrapper
{
public MyWrapper(SourceObject sourceObject)
{
this.Points = sourceObject.ListPoints();
}
[DataMember]
public List<decimal> Points { get; private set; }
}
EDIT: Or more lazily:
public class MyWrapper
{
public MyWrapper(SourceObject sourceObject)
{
}
private List<decimal> points;
[DataMember]
public List<decimal> Points
{
get
{
if (this.points == null)
{
this.points = sourceObject.ListPoints();
}
return this.points;
}
}
}
精彩评论