You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET7 Minimal API使用MapGroup时注入ILogger<T>的问题排查

.NET7 Minimal API MapGroup下注入ILogger的解决方案

你遇到的'MapWeatherForecastEndpoint': static types cannot be used as type arguments错误,核心原因是静态类不能作为ILogger<T>的泛型类型参数,C#语法禁止这种用法。以下是两种可行的解决办法:

方案一:使用非泛型ILogger并指定日志类别

将端点方法的ILogger<MapWeatherForecastEndpoint>替换为非泛型ILogger,通过显式指定日志类别来保持和原控制器日志一致的标识:

using Microsoft.Extensions.Logging;

public static class MapWeatherForecastEndpoint
{
    public static RouteGroupBuilder MapWeatherForecast(this RouteGroupBuilder buider)
    {
        buider.MapGet("/", WeatherForecast);
        return buider;
    }

    public static IResult WeatherForecast(ILogger logger, ISomeServices someServices)
    {
        // 以当前静态类作为日志类别输出
        logger.LogInformation(typeof(MapWeatherForecastEndpoint), "test");
        return TypedResults.Ok("WeatherForecast");
    }
}

也可以使用WithCategory扩展方法简化类别指定(需引用Microsoft.Extensions.Logging.Abstractions包):

public static IResult WeatherForecast(ILogger logger, ISomeServices someServices)
{
    var categoryLogger = logger.WithCategory(typeof(MapWeatherForecastEndpoint));
    categoryLogger.LogInformation("test");
    return TypedResults.Ok("WeatherForecast");
}

方案二:创建非静态日志类别类适配泛型ILogger

如果习惯使用泛型ILogger<T>,可以新建一个空的非静态类作为日志标识,避免静态类作为泛型参数:

// 新建非静态类用于日志类别
public class WeatherForecastLogCategory { }

public static class MapWeatherForecastEndpoint
{
    public static RouteGroupBuilder MapWeatherForecast(this RouteGroupBuilder buider)
    {
        buider.MapGet("/", WeatherForecast);
        return buider;
    }

    public static IResult WeatherForecast(ILogger<WeatherForecastLogCategory> logger, ISomeServices someServices)
    {
        logger.LogInformation("test");
        return TypedResults.Ok("WeatherForecast");
    }
}

这两种方法都能正常完成依赖注入,解决你的报错问题,同时保持日志的类别标识清晰。

内容的提问来源于stack exchange,提问作者Zulander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:05:17