title: Storing application level data in a WCF Service
body: <p>I am trying to create my first WCF Service and I am trying to store application data.</p>
  
  <p>I have created my ServiceContracts and DataContracts and the service is working.</p>
  
  <p>I now want to read some configuration data from a database and store this data at application scope so that the data is available to any subsequent requests as long as the service is alive.  That way I don't have to connect to the database each time I process a request.  I don't want to store the data in config files, the data already exists in said DB and I don't want to duplicate it.</p>
  
  <p>I have the following implemented and working.</p>
  
  <p>Note 1: I have removed the database code to keep the sample simple.</p>
  
  <p>Note 2: The MemoryCache class exists within the System.Runtime.Caching namespace.</p>
  
  <pre><code>private void LoadConfigData()
  {
      if (!MemoryCache.Default.Contains("ConfigData"))
      {
          CacheItemPolicy cachePolicy = new CacheItemPolicy() {
                    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5) };
  
          MemoryCache.Default.Add(
                    "ConfigData",
                    "ImagineThereIsDBDataHere",
                    cachePolicy);
      }
  }
  </code></pre>
  
  <p>Is this the right approach to use?</p>
  
  <p>This post mentions using the Application class and HttpContext:</p>
  
  <p><a href="https://stackoverflow.com/questions/9296981/read-global-application-property-from-wcf-service">Read Global Application property from WCF Service</a></p>
  
  <p>But I have neither of these available in my project currently.</p>
  
  <p>Is this thread safe, will I get race conditions if multiple requests are made to my service and the cache is empty?</p>
  
  <p>This is also my first question so if I have missed any detail let me know and i will update.</p>
  
  <p>Thanks.</p>