title: Calling stateful unmanaged C++ class from ASP.NET webservice
body: <p>I've inherited a half completed application that seems to use a model that I'm not sure can reliably work.</p>
  
  <p>It is a ASP.NET webservice that on each call loads a unmanaged C++ .DLL using</p>
  
  <pre><code>[DllImport ( "kernel32.dll" , EntryPoint = "LoadLibraryA" )]
  public static extern int LoadLibrary( string lpLibFileName );
  </code></pre>
  
  <p>and then makes a number of calls to it e.g.</p>
  
  <pre><code> [DllImport(@"MyUnamanagedDLL.dll")]
   public static extern string DoStuff( );
  </code></pre>
  
  <p>In the unmanaged C++ .dll it is using a singleton to hold state between calls. This is so that it only has to initialise once and load a bunch of slow stuff from disk and database rather than on each webservice call as this is too slow.</p>
  
  <p>So each call into the unmanaged .dll first calls Getinstance() if the instance is null it initialises it and reloads everything, if not it assumes its ready to go.</p>
  
  <p>FreeLibrary is not being called each time in the webservice as I assume this would cause the unmanaged class to have to be re-initialised each time.</p>
  
  <p>Is this model at all reliable? Can you ensure that if the webservice is shut down that the unmanaged state is cleaned up properly? Can you ensure you will relaible get a valid singleton instance between loadlibrary calls?</p>