My Blog

Using DOTNET_STARTUP_HOOKS in an NET Core Application

by lupok on giovedì 3 ottobre 2024 10:55

DOTNET_STARTUP_HOOKS is a powerful yet lesser-known feature of the .NET runtime that allows you to execute custom code before the main application starts. In this article, we'll explore how to use this feature in an ASP.NET Core application to perform advanced initialization or configuration operations.

What is DOTNET_STARTUP_HOOKS?

DOTNET_STARTUP_HOOKS is an environment variable that allows you to specify one or more assemblies containing code to be executed at application startup, before the main code runs. This can be useful for several reasons:

  1. Early resource initialization
  2. Runtime environment configuration
  3. Advanced logging or diagnostics
  4. Runtime-level dependency injection

Creating an ASP.NET Core Application with DOTNET_STARTUP_HOOKS

Let's see how to implement this feature step by step.

Step 1: Create the ASP.NET Core Application

Let's start by creating a new ASP.NET Core application with name "HostStartupHook":

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

Step 2: Create the Startup Hook Library

Now let's create a class library that will contain our startup hook:

internal class StartupHook
{
   public static void Initialize()
   {
      File.WriteAllText(@"C:\Temp\StartupHook.txt", "Hello from StartupHook!");
   }
}

 


Note that the 

StartupHook

 type is internal and in the global namespace, and the signature of the 

Initialize

 method is 

public static void Initialize()

.

 

Step 3: Configure DOTNET_STARTUP_HOOKS

In the launchSettings.json file: 

{
   ...

  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5248",
      "environmentVariables": {
         "ASPNETCORE_ENVIRONMENT": "Development",
         "DOTNET_STARTUP_HOOKS": "C:\\*******\\build\\StartupHook.dll"
      }
    }
  }
}


Now, when you run the application, the method "Initialize" of the class "StartupHook" will be called before the ASP.NET Core application starts.

DOTNET_STARTUP_HOOKS can be a powerful tool for customizing and optimizing the startup of your ASP.NET Core applications.

 

HostStartupHook.zip

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags