Search code examples
vb.netstatic-classesstatic-constructorvb.net-moduleshared-module

Execution sequence for a module constructor in a web application for VB.NET


I am trying to understand an execution sequence in a web application environment - basically I am using a module for various utility functions, including logging and initializing various global/shared variables. The website has several stand-alone pages and a few web-services.

We've had some issues with the website where one of the developers suggested that a piece of code that has to be executed first to initialize a crucial property (which happens in a module constructor, the property itself is NOT defined in a module, but rather on a 3rd party DLL and module simply initiates it in a constructor) is not being executed first. The reasoning behind that developer is "The module's constructor is only being called when a reference to it is found on a page that was opened.

So lets imagine there are 2 pages on our web application. Only Page2 has a reference to the MyModule. So the logic of this developer is, if the web site is restarted and the very first call is to Page1, which does not have any references to the module and therefore constructor is not called and therefore it does not initialize this property on a 3rd party DLL. Because of that, Page1 tries to use the 3rd party DLL with uninitialized property and it fails.

My counter to that is: Module is a shared class and its constructor, which is also shared is being initialized when the web application's assembly is loaded. According to my argument, it doesn't matter which page gets loaded first, constructor initiates the 3rd party tool when assembly loads and therefore the issue is somewhere else.

Am I right or am I wrong? I couldn't find the answer to my question, just some info on how Module is similar to C# static classes and yet its different.

Thank you

Public Module MyModule
    Sub New()
        Log("something")
        myThirdPartyDLLReference.InitializeVars()
        ...
    End Sub

Private Sub Log(ByVal logMessage as string)
    ' Do some logic. Log some information
End Sub 

End Module

Partial Class Page1
    Inherits Page

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        ' Do some logic, no references to MyModule
    End Sub
End Class

Partial Class Page2
    Inherits Page

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        ' Do some logic, initialize MyModule
        MyModule.Log("Page 2 initialized")
    End Sub
End Class

Solution

  • Your developer is right. Modules are only loaded when needed because the module list is empty when the program starts https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.modules?view=netframework-4.7.2

    this is also my experince and is shown in your experience also