I’m create AJAX Service with JSON and XML from this example.
In service.cs I make changes :
[ServiceContract(Namespace = "XmlAjaxService")]
public interface ICalculator
{
...
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
int GetTimersCallCount();
}
public class CalculatorService : ICalculator
{
private System.Timers.Timer timer = null;
private int timerCalls = 0;
public CalculatorService()
{
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
public int GetTimersCallCount()
{
return this.timerCalls;
}
}
On page javascript I do this:
function GetTimersTick() {
// Create HTTP request
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("This sample only works in browsers with AJAX support");
return false;
}
}
}
// Create result handler
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("result").value = xmlHttp.responseText;
document.getElementById("statustext").value = xmlHttp.getAllResponseHeaders();
}
}
// Build the operation URL
var url = "service.svc/";
url = url + "GetTimersCallCount";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send();
}
But When I press button with this function I’m get from service 0. What is wrong?
The reason is that there is not one single instance of your
CalculatorServiceclass. It gets recreated on every new call to the service.To enable single instance mode, use the following attribute on your service implementation class:
Be aware that when using single instance mode, you may need to synchronize calls to your service methods. In your specific example this isn’t necessary since you are only reading and writing a 32 bit integer (which is an atomic operation).