Search code examples
c#c++multithreadingvisual-studiostartup

C# Class Library How To Add Startup Code


Below is how to write C++ functionality to do something when the DLL is first called on the server. How does one do this in C# Class Library? The Startup in properties is grayed (disabled) for Class Library project out in Visual Studio but need to be library as I'm using it in my web application as reference. And not sure how to write an equivalent in C# so I could do some code to log events when the dll is loaded or started.

BOOL WINAPI DllMain(
  HINSTANCE hinstDLL, // handle to DLL module
   DWORD fdwReason, // reason for calling function
   LPVOID lpReserved ) // reserved
{
   // Perform actions based on the reason for calling.
   switch( fdwReason )
   {
     case DLL_PROCESS_ATTACH:
        // Initialize once for each new process.
        // Here is where the module POST should be invoked
        // Return FALSE to fail DLL load in case POST fails
     break;
     case DLL_THREAD_ATTACH:
        // Do thread-specific initialization.
     break;
     case DLL_THREAD_DETACH:
     // Do thread-specific cleanup.
     break;
     case DLL_PROCESS_DETACH:
     // Perform any necessary cleanup.
     break;
     }
     return TRUE; // Successful DLL_PROCESS_ATTACH.
}

Solution

  • I'm using it in my web application as reference

    If it's hosted in IIS you can use PreApplicationStartMethodAttribute to run code very early on in your application startup.

    This allows you to perform once-off initialisation but might force the initialisation earlier than necessary, because IIS will run your code as the application starts up rather than the first time you use classes in the assembly.

    how to write an equivalent in C# so I could do some code to log events when the dll is loaded or started.

    DllMain has some pretty severe restrictions. You can't expect to be able to log events reliably from DllMain anyway, so there's no precedent for "I can do it like this in C++ now how do I do it in C#".