I created the following class:
public static class PingEndpoints
{
public static void Endpoints(this WebApplication application)
{
var group = application.MapGroup("ping");
group.MapGet("", PingMethod);
}
internal static IResult PingMethod([FromServices] ILogger<PingEndpoints> logger)
{
try
{
logger.LogInformation("Test log");
var pingInfo = new PingInfo(DateTime.UtcNow, "Ping successfull");
return Results.Ok(pingInfo);
}
catch (Exception ex)
{
//wanted to log error
}
}
}
Above class is registered in the program.cs like below:
var builder = WebApplication.CreateBuilder(args);
...
var app = builder.Build();
...
app.Endpoints();
app.Run();
Fyi, I can inject any dependency into the PingMethod as a parameter.
Now, In the above class compiler gives me an error (i.e static types can not be used as type arguments) while injecting an instance of logger into the PingMethod method.
Can anyone suggest how can I inject Logger with the same class which I am using Here, I am creating many other endpoints as well.
You can use any non-static class:
public static class PingEndpoints
{
internal static IResult PingMethod([FromServices] ILogger<PingInfo> logger)
{
// ...
}
}
Or inject logger factory and create logger from it:
public static class PingEndpoints
{
internal static IResult PingMethod([FromServices] ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(nameof(PingEndpoints));
// or to match the generic logger approach:
var logger = loggerFactory.CreateLogger("PingEndpointsNamespace.PingEndpoints"));
// ...
}
}