Handling "System.AppDomainUnloadedException was unhandled" exception in Windows Azure service

 

When running a web service application Windows Azure development fabric, in some cases you may hit the following error:

 

 System.AppDomainUnloadedException was unhandled

 Message: Attempted to access an unloaded AppDomain.

 

 

This issues has been discussed in details in Azure forums: https://social.msdn.microsoft.com/Forums/en/windowsazure/thread/7c8967ba-694f-4125-9425-2962af74e974

 

First I would say that there could be several different
reasons for this issue however even if you received this error in your
development fabric, your service will have no problem on Cloud due to this
exception. There could be several
ways to solve this issue and a few of them are as below:

 

  1. Please check and delete the contents of Environment Variables
    called _CSRUN_STATE_DIRECTORY. Due to a known issue, the data in this
    folder could be corrupted.
  2. Create a brand new VS2010 cloud application with any template
    code, and compile it first to ensure there is no error. And then add your code
    to it step by step and keep checking what piece of code is giving this error.
  3. If you have any non C# compiler references (i.e. J# etc) in your
    web.config then remove it completely
  4. Please set all your references have Copy Local set to
    true.

What I found while working with a partner is that, following change in Global.asax solved this problem:

  • Original:         <%@ Application Codefile="Global.asax.cs"
    Inherits="<Your_Service_Name>.Global" Language="C#" %>
  • Change to:    <%@ Application Language="C#" %> 

The purpose for this change is to remove your code dependency from your global code file and code-behind class for the application class it is inheriting, if applicable.