<Problem>
1 Create a project with the C # Asp.net grpc service template.
2 Modify Program.cs as follows.
Register the function in app.Lifetime.ApplicationStarted.Register for the process you want to execute after starting the server.
Program.cs
using Asp.net.GrpcService1;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
var app = InitHelper.InitApp(builder);
app.Run();
InitHelper.cs
using Asp.net.GrpcService1.Services;
namespace Asp.net.GrpcService1
{
public class InitHelper
{
public static WebApplication InitApp(WebApplicationBuilder builder)
{
var app = builder.Build();
app.Lifetime.ApplicationStarted.Register(
() =Console.WriteLine("started!")
);
// Configure the HTTP request pipeline.
app.MapGrpcService<GreeterService>();
app.MapGet("/", () ="Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
return app;
}
}
}
3 Run the project.
4 If the port of the server to be started is already used by another application, an exception will occur in app.Run ().
Exception) System.IO.IOException:'Failed to bind to address http: // localhost: xxxx.'
<What you want to hear>
How should I code to execute the process registered in app.Lifetime.ApplicationStarted.Register even if app.Run () fails?
However, I don't want to enclose app.Run () in Program.cs with try catch.
×
try {
app.Run ();
} catch {
// Console.WriteLine("started!")
}
Because InitHelper is a common module and InitHelper is referenced from multiple Program.cs, I don't want to change Program.cs.
Please let me know if you have an alternative.