最小API -如何在静态类中使用ILogger



我创建了以下类:

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
}
}
}

上面的类在program.cs中注册如下:

var builder = WebApplication.CreateBuilder(args);
...
var app = builder.Build();
...
app.Endpoints();
app.Run();

我可以把任何依赖项作为参数注入到PingMethod中。

现在,在上面的类中,当向PingMethod方法注入logger的实例时,编译器给了我一个错误(即静态类型不能用作类型参数)

有谁能建议我如何用我正在使用的相同类注入Logger吗?这里,我也创建了许多其他端点。

您可以使用任何非静态类:

public static class PingEndpoints
{
internal static IResult PingMethod([FromServices] ILogger<PingInfo> logger)
{
// ...
}
}

或者注入logger工厂并从中创建logger:

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"));
// ...
}
}

最新更新