praful surve praful surve - 1 month ago 20
C# Question

How to access data member values in WCF?

Following is my WCF code-

public class Detect : IDetect
{
[DataMember]
string landMark1, landMark2, landMark3;
[DataMember]
int pingCounter;

public void setLandMark(string lm1, string lm2, string lm3)
{
landMark1 = lm1;
landMark2 = lm2;
landMark3 = lm3;
}

public void setPingCounter(int p)
{
pingCounter = p;
}
}


When I debug my code and access setLandMark() it assigns the parameters passed by client object to the private data member of the class, but when I call the other function setPingCounter() it shows the landmark data members as null.

suppose following is my code for client side-

DetectClient proxy = new DetectClient();
proxy.setLandMark("google.com", "yahoo.com", "facebook.com");
proxy.setPingCounter(5);


When setPingCounter is called landmark1, landmark2, landmark3 are initialized to null. I guess every call to method initiates different client object. If is it so, how can I avoid this?

Answer

I suppose you creating WCF service? If so, you probably forget to apply right ServiceBehavior attribute to your service implementation. By default it will create service for each request to its contract.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]

Add this to your Detect service implementation and your service will be single for every request to contract.