I wrote a WCF service, but the data stored in the Service implementation doesn't persists between calls, not even if stored in a static variable. What can I do?
The service implementation is as follows:
public class Storage : IStorage
{
protected static object[] _data;
#region IStorage Members
public void Insert(object[] data)
{
lock (_data)
{
_data = _data.Concat(data).ToArray();
}
}
public object[] SelectAll()
{
lock (_data)
{
return (object[])_data.Clone();
}
}
#endregion
}
The service host is a console application:
static void Main(string[] args)
{
ServiceHost serviceHost =
new ServiceHost(typeof(TimeSpanStorage));
serviceHost.Open();
Console.WriteLine("Service running. Please 'Enter' to exit...");
Console.ReadLine();
}
WCF services use SOAP by default, but the messages can be in any format, and conveyed by using any transport protocol like HTTP,HTTPs, WS- HTTP, TCP, Named Pipes, MSMQ, P2P(Point to Point) etc.
WCF services can be hosted in any managed application. This is the most flexible option because it requires the least infrastructure to deploy. You embed the code for the service inside the managed application code and then create and open an instance of the ServiceHost to make the service available.
This is referred to as a self hosting WCF service, the exact meaning of Self Hosted is that it hosts the service in an application that could be a Console Application or Windows Forms and so on. Earlier we saw what a WCF Service is in the . Net environment. We can host a WCF service in IIS and a Windows service also.
By default WCF instanceMode is set to Per call, meaning data used in the service is specific to that client for that method call.
On your implementation try adding
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Single)]
public class MyService: IService
This makes the service essentially a singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With