4

I have a pecular problem in my WCF in the web services layer.

When I instantiate a private member (_Wagon) of my class (This instantiation is not null) in WCF, after few seconds, it's become null.

I've been trying to diagnose the problem, but no result so far.

So I'm turning to you people to help me solve this problem.

Thank you.

Hence there is my code :

[DataContract]
public class RemoteWagon
{
    private readonly IWagon _Wagon;

    public RemoteWagon(IWagon Wagon)
    {
        _Wagon = Wagon; //_Wagon isn't null here
    }

    ~RemoteWagon()
    {
        Trace.WriteLine("Do nothing");
    }       

    [DataMember]
    public RemoteBreakpoint Breakpoint
    {
        set
        {
            if (value == null)
            {
                _Wagon.Breakpoint = null; //_Wagon member is NULL...
            }
            else
            {
                //... useless code in this context.
            }
        }
    }       
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Clément
  • 43
  • 5
  • Is all the instantiation and working with the `RemoteWagon` class happening the context of a single WCF call, or across multiple calls? – mellamokb Apr 02 '12 at 19:24
  • 1
    Has the instance of `RemoteWagon` been sent across the wire from client to server between the two times you check?? Basically, WCF will **only** serialize the **public shape** of a class - everything that's marked with a `[DataMember]` attribute. Anything else will **not** be transported across the wire and thus will not be available on the other side of the communication link. – marc_s Apr 02 '12 at 19:27

2 Answers2

2

This would happen if your class had been serialized and deserialized by DataContractSerializer (for example when sending data between client and server)

Some reference: DataContractSerializer doesn't call my constructor?

If this is the case, then one possible solution, that worked for me: https://stackoverflow.com/a/9419943/724944

So a quick check&fix for this problem (I assume that you want to initialize the field yourself and not serialize it) would be to create method:

[OnDeserializing]
private void OnDeserializing(StreamingContext c)
{
    _Wagon = initializeWagon();
}

however, as you probably noticed, you won't be able to pass Wagon during deserialization - you'll have to initialize it differently.

On the other hand, If you want _Wagon serialized, then expose it as public [DataMember] property

Community
  • 1
  • 1
surfen
  • 4,644
  • 3
  • 34
  • 46
1

It seems that if you want _Wagon serialized you should mark it as a DataMember and ditch the "readonly" on it. If you don't want it serialized, show us your code to construct and fill this object.

Brannon
  • 5,324
  • 4
  • 35
  • 83