Assembly Initialization
Nicolas Galler | December 31, 2006It appears that there is no facility in .NET to automatically call an initialization method when the assembly is loaded. This is a bit annoying for libraries since they will often require some initialization. So far I have found 2 work-around, neither of which are terribly satisfying:
- Have a static initializer on the classes that are going to be called first when using the library. Obviously this is not usable in every case…
- Register a handler for the assembly load event – this handler could then check the assembly for an initializer class. The easiest way I have found to achieve that was to define the initializer (with initialization done either in the constructor or in a static initializer) as an assembly level attribute, stick it on the assembly for the library, and have the assembly load event handler call the GetCustomAttributes method. I was actually hoping that .NET would be tricked into calling my attribute since it was an assembly attribute, sadly it seems it does not actually instantiate those attributes until someone tries reading them… So with this method I still need to have one initializer called manually to initialize the event handler.
There was a 3rd alternative which would be to just load all the types in the assembly whenever it is loaded (i.e. from the Load event handler)… then any static initializer would be called… seems like it could be a performance hit though so I decided to go with the more explicit approach.





