Thanks to an advanced initialization scenario (as warned about in the documentation), we're leveraging the ModuleInitializer
attribute to run some code at module-initialization time like so...
[ModuleInitializer]
public static void InitModule() {
// Do something with the app here
}
However, we found differences in behavior depending on how the module was loaded. Specifically...
- If loaded via a project reference/dependency,
Application.Current
property is not set. - If dynamically loaded via reflection,
Application.Current
property is set.
Since we need access to the current application for part of our initialization (it doesn't have to run right then, only when the application exists), our initial approach was during our initializers, test if Application.Current
was set. If so, use it as normal. If not, build some sort of 'actions queue' that would queue up all the actions we want to run, then from within the Application class's constructor, process that queue.
As such, the above changed to this...
[ModuleInitializer]
public static void InitModule() {
void appRelatedInitialization(Application application) {
// Do something with the app here
}
if(Application.Current is not null) {
appRelatedInitialization(Application.Current);
}
else {
// Add the method to a queue of actions which take an Application as an argument
Globals.AppInitQueue.Add(appRelatedInitialization);
}
}
But then we ran into an application that doesn't use an Application
subclass, instead opting for a main
method and doing all the app configuration there.
Of course we could add the queue processing there, just like we could with an initializer and subclassing, but what we really want is to know when the application is instantiated regardless of the type of application it is and have this execute automatically for us so we don't have to add it anywhere.
The issue is Application.Current
is a static POCO property that doesn't use INotifyPropertyChanged
or similar, so we're not sure how to determine when the Application instance is set. We don't want to use brute-force polling either as that is the worst kind of code-smell.
So, how can we determine when the current Application object is created and assigned to the running process?