If a static constructor throws an exception, the runtime doesn't invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain. So, only way to come out this situation is Application recycle/restarts.
This can be a very rare scenario occurring intermittently and can become difficult debug. I have seen this issue happening WCF or Asp.Net impersonation.
Consider below exception:
System.Security.SecurityException: Requested registry access is not allowed. Once this occurs, every user gets the exception, until I restart the application.
Anyone who has knowledge of debugging, obvious try to see the registry path being accessed using tools like Process Monitor - Sysinternals | Microsoft Learn. The problem when I browse the page again with procmon running, I don't see any call made to registry of interest.
This can also happen to file access. So how to debug this?
First step is to understand below:
In my case, all the above is true. Let's look at the source code:
for demonstration purposes, I'm using an aspx page as my source code. I've enabled Asp.Net impersonation (Impersonation in ASP.NET applications - ASP.NET | Microsoft Learn) with IIS classic pipeline.
I have a class with a static constructor accessing a restricted registry folder. This can be a logwriter, DBcontext etc. in real world. Since I have impersonation enabled, this code executes with logged user context.
Note the below points about static constructors - Static Constructors - C# Programming Guide - C# | Microsoft Learn:
So, if the first request when the process starts is made by a user with no access to the registry of interest, constructor throws exception.
The constructor is not invoked again even if a user with access browses the page. When the App is restarted and a user with access makes the request, the constructor runs fine. This is what makes it difficult to debug, the intermittency of the issue!
How to resolve this:
Happy debugging!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.