Static Constructors and Plug-In Security...
After reading the CLI spec, there are some things about static initializers (type initializers) that appear fairly odd. I started reading this portion of the spec after Peter Torr referenced it in his post (http://weblogs.asp.net/ptorr/archive/2004/01/27/63308.aspx). He pointed out that you can't guarantee your static initializer is only called once unless you explicitly hide it from existence. Wow, so a type initializer can be run more than once, that is something you might not normally think of, but I guess it can happen.
So I got to thinking about when the static initializer was actually going to be called. I remember hearing some, word, back in the day, about the initializers being called when the assembly was loaded. This had some performance ramifications though when assemblies grew larger. Then I remember hearing about the initializers possibly getting delay loaded until the type was actually used. I never really did find out exactly how it worked, but reading the CLI spec opens things up a bit. Basically, you can't guarantee that a static initializer has been called even after a static method or property has been accessed. There is a special designation, beforefieldinit, that allows all of the guarantees about them to be turned off.
So, you can't guarantee when a static initializer is run, you can't guarantee I'm guessing that it will even be run unless you actually make use of the static fields. Now, if things were a bit more explicit here, it would be possible to actually program some security around your plug-in library. Basically, what I'm thinking is that you can probably load the assembly within your normal thread, but that you'll need to create instances of the type and run any methods of the type from the secured plug-in thread. That way if the static initializer hangs you can cancel things out. Unfortunately I'm making an assumption here with regards to security. To be absolutely safe I'd also have to load the assembly on a thread I could cancel. So out pop some questions:
1. How do I need to load and use the assembly to guarantee the type initializer is run under my secure thread? Can I safely load the assembly without worrying about type intializers running? Then transfer all other work processes over to the secure thread?
2. Are managed threads robust enough to cancel out and abort when a type initializer is hanging the thread?
Statics can potentially be very dangerous to a secure plug-in framework because of the uncertainty of when they'll be run and the uncertainty of what form of actions they'll take. On the opposite side of the street, plug-ins can benefit heavily from static look-up tables and helper functions. You might adopt a factory system into your framework similar to the System.Net namespace and the WebRequest.Create method.