Monday, March 7, 2011

Reuse/cache datatable in a web service

I have a web application that pulls a datatable and displays results. Due to the nature of the business all of the business rules are incorporated in dlls that the web app must pull from. Because there are multiple site and we don't want to include the core dll's in all of the many apps that are deployed we consolidate any calls to the core dll's into a webservice. This helps when the core dll's are updated that only one new app (i.e. the web service) needs to be pushed.

With this architecutre I have found that anyone logging into any web app is causing multiple calls to the database in order to get a datatable that is then parsed. The datatable in question changes slowly and I only need to refresh it maybe once every 4-6 hours.

I am familiar with storing things like this in session when a user wants to see different views of the same datatable. However with the webservice session doesn't really apply. What is a good method for caching a datatable in the webservice so that we are not making repeated expensive trips to the database.

The webservice and the apps are all in C# and ASP.NET 2.0, and we are using VS2005.

From stackoverflow
  • You could store any data in memory for as long as you want with memcached. It runs on Linux and Windows and they also have several api implementations with C#.

  • Cheap option #1: create the datatable as a local static variable to your web service class. Populate the datatable object in a static constructor to the class. The datatable object will be available to your webmethod when the service is queried for the first time as well as any app worker process recycles.

    //pseudo-code

    class MyWebMethods {

    private static DataTable localDataTable; static MyWebMethods() { localDataTable = new DataTable(); //Do whatever else is needed here to populate the table }

    [WebMethod] public string GetSomeData(int id) { //Query localDataTable using parameter info //return result } }

    Cheap option #2: similar approach, consider ASP.Net Cache (System.Web.Caching.Cache). Same loading process as above, but different storage.

  • As a really cheap way (but it exists), you can use the CacheDuration property of the WebMethod arribute, which will cache the results of the web method call. More info at:

    http://msdn.microsoft.com/en-us/library/byxd99hx(VS.71).aspx#vbtskusingwebmethodattributecacheduration

    That might help, just a thought...

0 comments:

Post a Comment