Thursday, December 13, 2018

.NET Core 2.2: Executing Code Prior to Main Method

Last week .NET Core 2.2 was released with some nice features and in this post, let’s see one of them which is executing code before the Main method.

As we all know the Main method is the entry point of a program. But .NET Core 2.2 is introducing this feature called Host startup hook and it provides a mechanism to execute code before executing the Main method.

I have created two class library projects named StartupHook1 and StartupHook2 and both of them are targeting .NET Core 2.2. Inside both of the projects, I am adding a class named StartupHook.
using System.Diagnostics;
using System.Reflection;
 
internal class StartupHook
{
    public static void Initialize()
    {
        Debug.WriteLine($"{Assembly.GetExecutingAssembly().GetName().Name} is called.");
    }
}

Note: The type must be named StartupHook without any namespace and it should be internal. And inside the class, we should have a static method named Initialize. For the sake of the post, I am just logging a message inside the method.

When I build the projects, I will have two dlls, StartupHook1 and StartupHook2.

Now take an existing .NET Core 2.2 application. For the demo, let’s just create an ASP.NET Core 2.2 Web Application. And to link the web application and the two class libraries (which are startup hooks), we need to add an environment variable named DOTNET_STARTUP_HOOKS to the web application as follows. We can easily do that by going to web application project properties and adding an environment variable.

image
ENVIRONMENT VARIABLE
It’s basically something like below.
DOTNET_STARTUP_HOOKS=SomePath\StartupHook1.dll;SomePath\StartupHook2.dll
Now I will just modify the web applications Main method to add some logging.
public static void Main(string[] args)
{
    Debug.WriteLine("Main is called.");
 
    CreateWebHostBuilder(args).Build().Run();
}

Now if I run the ASP.NET Core web application, I am seeing the below.

image
Debug Output
You can see that the Initialize methods in both StartupHook1 and StartupHook2 has been called before the actual entry point. And the execution order is the order we have defined the hooks in the environment variable.

Isn’t it nice.

For more information,
   Host startup hook

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment