Summary
This article discusses various methods to run code once the application starts in .Net6.
Abstract
The article "Run code once the application starts in .Net6" provides insights into executing code when an application starts in .Net6. It suggests two primary methods: writing code in the Program.cs file and using Hosted Services with the IHostedService interface. The Program.cs file allows code execution between builder.Services() for dependency registration or between app() for middleware configuration. Hosted Services, typically used for long-running background tasks, have StartAsync and StopAsync methods executed when the application starts and stops. Additionally, the article mentions using IHostApplicationLifetime events, such as ApplicationStarted, ApplicationStopping, and ApplicationStopped, to register callbacks.
Opinions
- The author assumes the reader is a developer who may need to log something, populate data in memory, run background tasks, publish an event, or read configuration when the application starts.
- The author suggests that the StartAsync method in Hosted Services should return quickly to avoid blocking other hosted services.
- The author emphasizes that the OnStarted event is published after the application host has fully started, including services and request processing pipeline configuration, and the app has started serving web requests.
- The author recommends trying out an AI service that offers similar performance and functions to ChatGPT Plus(GPT-4) but at a more cost-effective price of
6/month (Special offer for 1/month).