C++ singletons and .NET AppDomains

  • Thread starter Thread starter Yevgeny Menaker
  • Start date Start date
Y

Yevgeny Menaker

I am struggling with the following:
We have legacy classes written in C++ that are compiled to static
libraries. Some of these classes are singletons. In order to make
these classes available to C#, we wrapped them with Managed C++. The
wrapper classes works fine in most of the cases. However, if they are
used in ASP.NET Web Applications a problem may arise in the following
scenario:
Step 1: The first Web Application starts in its own AppDomain inside
aspnet_wp.exe process and creates wrapper singleton class, which in
turn creates underlying unmanaged C++ singleton.
Step 2: We change the web.config file of our Web Application. This
causes unloading AppDomain of the Web Application.
Step 3: Web Application starts again and a new AppDomain is loaded
upon HTTP request.
Step 4: A new AppDomain gets an instance of Singleton. Since the
underlying C++ singleton has a static variable holding pointer to
singleton instance, this instance lives until aspnet_wp.exe process
exits. So, when trying to access this instance from a new AppDomain
raises AppDomainUnloadedException, since we access memory that was
allocated for an old AppDomain.


The solution I found is using Remoting and create wrapper Singleton
together with the underlying C++ singleton in the "remote" AppDomain.
However, there is too much overhead. Another way is, of course, to
rewrite the unmanaged C++ class and make it non-singleton.

Are there any other cleaner solutions for this problem?

Many thanks,
Yevgeny Menaker
Author, Software Engineer.
 
why don't you update your logic to cause the singleton instance to go away
when the application domain unloads?
 
Back
Top