Wednesday 21 February 2024

ASP.NET Hosting Tutorial: ASP.NET Core with Hosted Service & Lifecycle Events

Leave a Comment

ASP.NET Core is a strong framework for creating modern online apps. It includes a valuable "hosted services" capability that enables developers to conduct background operations within an ASP.NET Core application. Using lifecycle events, developers can have fine-grained control over the startup, execution, and termination of these background operations. This feature makes asynchronous operations more efficient. In this post, we will look at the world of ASP.NET Core hosted services and how lifecycle events can improve their usefulness.

Understanding Hosted Services.
Hosted services in ASP.NET Core are long-running background processes that operate independently of the request processing pipeline. They are commonly used for background processing, periodic data synchronization, and other asynchronous operations that do not require immediate user engagement. Hosted services use the IHostedService interface, which defines how to start and stop the service. 

public interface IHostedService
{
    Task StartAsync(CancellationToken cancellationToken);
    Task StopAsync(CancellationToken cancellationToken);
}

public interface IHostedService
{
    Task StartAsync(CancellationToken cancellationToken);
    Task StopAsync(CancellationToken cancellationToken);
}

The StartAsync method is called when the application starts, and the StopAsync method is called when the application is shutting down. These methods provide an opportunity to initialize resources, start background processing, and perform cleanup tasks.

Implementing a Hosted Service

Let's create a simple example of a hosted service that performs the background task of printing a message every few seconds. First, create a new class that implements the IHostedService interface.

public class BackgroundPrinter : IHostedService, IDisposable
{
    private Timer _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        Console.WriteLine("Background task is running...");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?. Dispose();
    }
}

In this example, we use a Timer to execute the DoWork method every 5 seconds. The Dispose method is implemented to clean up any resources used by the service.

Registering the Hosted Service

Once the hosted service is implemented, it must be registered with the ASP.NET Core dependency injection container. This can be done in the ConfigureServices method of the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService<BackgroundPrinter>();
}

Now, when the application starts, the BackgroundPrinter service will start running in the background.

Leveraging Lifecycle Events
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Use middleware, configure routing, etc.

    app.ApplicationStarted.Register(() =>
    {
        // Perform actions when the application has started
    });

    app.ApplicationStopping.Register(() =>
    {
        // Perform actions when the application is stopping
    });

    app.ApplicationStopped.Register(() =>
    {
        // Perform actions when the application has stopped
    });
}

By leveraging these lifecycle events, developers can coordinate the initialization and cleanup of resources with the startup and shutdown of the application.

Best ASP.NET Core 8.0.1 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment