.Net: Running code when assembly is loaded

后端 未结 6 514
不思量自难忘°
不思量自难忘° 2020-11-27 05:02

Is it possible to run some code when an assembly is loaded, without doing anything specific in the loading code? What I am looking for is like a static constructor on a type

6条回答
  •  佛祖请我去吃肉
    2020-11-27 05:21

    There are 3 options to initialize a .NET Assembly:

    1. You write a static function Init() or Main() in your Assembly to be initialized and call this function by reflection from the C# code that loads this Assembly.
    2. Write a Managed C++ Assembly where you put your code in DllMain(). Be careful because your code will be executed in the Loader Lock where several things are forbidden (like loading other DLL's,...). But you can start a new thread that does ANY initialization stuff. (About LoaderLock: https://msdn.microsoft.com/en-us/library/ms173266.aspx) (About DllMain: C# to C++/CLI to C DLL System.IO.FileNotFoundException)
    3. You compile a pure C# Assembly and modify the compiled DLL to add a module initializer code like explained here: http://einaregilsson.com/module-initializers-in-csharp/ The disadvantage of this method is that the initialization function is not called immediately when the assembly is loaded into the process. But it is called before anything else in the assembly is first accessed.

提交回复
热议问题