object reference not set to an instance of an object" - Not "initialized" through WCF?
-
Could one please give me a hit, or probably confirm a bug?
I have a custom class, something like this:
[DataContract]
public class CompositeType
{
ClassX x = new ClassX();
[DataMember]
public string Field
{
get { return x.X; }
set { x.X = value; }
}
}
public class ClassX
{
public string X;
}
When used in a WCF service, I get a "object reference not set to an instance of an object". I have also tried using a class initializer (public CompositeType()), where I do the new ClassX(); but I do get the same result...
Does anyone know why? Is there a solution for it?
Thankx, Cheers Harry
Answers
-
On deserialization, WCF does not call the constructors or field initializers of the type it's creating. If you need to perform some initialization on deserialization, you need to use the OnDeserializing callback (http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx). The example below should work for you:
[DataContract]
public class CompositeType
{
ClassX x;
[DataMember]
public string Field
{
get { return x.X; }
set { x.X = value; }
}
public CompositeType()
{
Initialize();
}
[OnDeserializing]
public void OnDeserializing(StreamingContext ctx)
{
Initialize();
}
private void Initialize()
{
this.x = new ClassX();
}
}
public class ClassX
{
public string X;
}
本文讨论了在使用WCF服务时遇到的对象引用未设置到对象实例的问题,并提供了解决方案,即通过OnDeserializing回调进行对象初始化。
3万+

被折叠的 条评论
为什么被折叠?



