Is there a way in c# console applications to automatically run a piece of code before main function

746 Views Asked by At

I recently came across the preapplicationstartmethod that is there for asp.net applications. I need something like that for console apps. I have a external logging dll. I want to configure logging such that on referencing the dll some code of logging automatically gets executed. I just need to call a class constructor before any other code is executed. Any help would be appreciated.

Like Application Insights automatically collects perf counters on adding reference to the mvc application and adding instrumentation key to config file. I need something like that for console apps.

2

There are 2 best solutions below

0
On BEST ANSWER

Any code in static initializer of the class containing Main will be executed prior to entering Main:

public class MyConsoleApp {
    static MyConsoleApp() {
        Console.WriteLine("I run before Main");
    }
    public static void Main(string[] args) {
        Console.WriteLine("Main");
    }
}

Demo.

3
On

If you just search a way to execute code before entering Main, dasblinkenlight already gave you an answer. But if you want to get code executed just by referencing a library, I do not think this is possible at all.

The code in your library is only executed, when something from the library is used, even static constructors. You can watch the time your library gets loaded, if you add breakpoints and then wait on execution until they turn fully red.

Additional opportunity:

If you do not want to edit the code of the application, add an application, which just calls your logger initialization code and after that the Main of your original application.