Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a WCF service with in-memory persistent storage?

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();
}
like image 343
Jader Dias Avatar asked Dec 01 '09 13:12

Jader Dias


People also ask

Does WCF use SOAP?

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.

How is WCF service hosted?

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.

What is self hosted WCF?

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.


1 Answers

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.

like image 199
MattC Avatar answered Oct 13 '22 00:10

MattC