Home > Mobile >  How to create try-finally method for ASP.Net Core 6 application
How to create try-finally method for ASP.Net Core 6 application

Time:09-27

In previous versions of .Net Core, we had a public static void Main(string[] args) method in program.cs. In this method we could use a try-(catch)-finally block, where the finally is executed when the application is closed.

In .Net Core 6 has the program.cs changed and there is no Main() method anymore. How to create a 'finally method' that is executed once the applications stops/closes.

I tried to do it right away in program.cs, but then the finally-block is executed immediately.

Example (dummy) code program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

SomeAPI _someAPI = CreateSomeAPI();

try
{
    _someAPI.Connect();
}
catch (Exception ex)
{
    Console.WriteLine(string.Format("Exception was throw {0}", ex.Message));
}
finally
{
    _someAPI.Disconnect();
}

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();

CodePudding user response:

The whole app initialization code should be wrapped in the try statement

SomeAPI _someAPI = CreateSomeAPI();

try
{
    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.
    builder.Services.AddRazorPages();

    _someAPI.Connect();

    var app = builder.Build();
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.MapRazorPages();
    app.Run();
}
catch (Exception exception)
{
    Console.WriteLine(string.Format("Exception was throw {0}", ex.Message));
}
finally
{
    _someAPI.Disconnect();
}
  • Related