Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my abstract base class's constructor not called when an object is initialized by the WCF deserializer?

Question in title... In short - I have a WCF service exposing operations that return entity classes. The client-side classes inherit from an abstract base class instead of the default System.Object. The abstract base class has a default constructor defined. When calling one of the service methods I would expect that constructor to get called when the datacontract serializer materialize the returned objects. However, the constructor is not called. If on the other hand I create an instance of the entity class myself then the abstract class constructor is called.

Why, oh why, and is there a workaround? Or did I miss something - is there another constructor signature that is called by the datacontract serializer when materializing objects? If not, how can the datacontract serializer materialize objects without calling the constructors the same way that a "new SomeClass()" call would do? Or did I drink too much coffee today (only had 2 or 3 cups so far)?

like image 798
KristoferA Avatar asked Aug 26 '09 10:08

KristoferA


1 Answers

WCF (and DataContractSerializer in particular) doesn't use constructors. No, really (it uses FormatterServices.GetUninitializedObject to create raw objects).

It is expected that all data will be initialized either by the serializer, or for non-serialized fields - by serialization callbacks that you add (for example, via [OnDeserialized]).

like image 188
Marc Gravell Avatar answered Sep 21 '22 05:09

Marc Gravell