views:

800

answers:

4

I have a web service that queries data from this json file, but i don't want the web service to have to access the file every time. I'm thinking that maybe i can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service?

Update: Both suggestions, caching and using static var, look good. Maybe i should just use both so i can look at one first, if it's not in there, use the second one, if it's not in there either, then i'll look at the json file.

+1  A: 

ASP.NET caching works just as well with Web services so you can implement regular caching as explained here: http://msdn.microsoft.com/en-us/library/aa478965.aspx

IceHeat
+2  A: 

What about using a global or static collection object? Is that a good idea?

Hertanto Lie
+4  A: 

Extending on Ice^^Heat's idea, you might want to think about where you would cache - either cache the contents of the json file in the Application cache like so:

Context.Cache.Insert("foo", _
                 Foo, _
                 Nothing, _
                 DateAdd(DateInterval.Minute, 30, Now()), _
                 System.Web.Caching.Cache.NoSlidingExpiration)

And then generate the results you need from that on every hit. Alternatively you can cache the webservice output on the function definition:

<WebMethod(CacheDuration:=60)> _
Public Function HelloWorld() As String
    Return "Hello World"
End Function

Info gathered from XML Web Service Caching Strategies.

Mark Glorie
+2  A: 

To echo klughing, if your JSON data isn't expected to change often, I think the simplest way to cache it is to use a static collection of some kind - perhaps a DataTable.

First, parse your JSON data into a System.Data.DataTable, and make it static in your Web service class. Then, access the static object. The data should stay cached until IIS recycles your application pool.

public class WebServiceClass
{
    private static DataTable _myData = null;
    public static DataTable MyData
    {
        get
        {
            if (_myData == null)
            {
                _myData = ParseJsonDataReturnDT();
            }
            return _myData;
        }
    }

    [WebMethod]
    public string GetData()
    {
        //... do some stuff with MyData and return a string ...
        return MyData.Rows[0]["MyColumn"].ToString();
    }
}
Terrapin