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

Minimal API:静态类中如何注入并使用ILogger

解决方案:静态类Minimal API中注入Logger的问题

报错原因

C#禁止将静态类型作为泛型类型参数使用,因此ILogger<PingEndpoints>的写法不合法(PingEndpoints是静态类)。以下是几种无需重构整个类结构的解决办法:

方案一:在扩展方法中预获取Logger并传递

保留静态类和静态方法,在端点注册时从服务容器获取指定类别的Logger,通过闭包传递给处理方法:

public static class PingEndpoints
{
    public static void Endpoints(this WebApplication application)
    {
        // 针对PingEndpoints创建Logger
        var logger = application.Services.GetRequiredService<ILoggerFactory>()
            .CreateLogger(typeof(PingEndpoints));
        var group = application.MapGroup("ping");

        // 通过闭包将logger传入PingMethod
        group.MapGet("", () => PingMethod(logger));
    }

    internal static IResult PingMethod(ILogger logger)
    {
        try
        {
            logger.LogInformation("Test log");
            var pingInfo = new PingInfo(DateTime.UtcNow, "Ping successful");
            return Results.Ok(pingInfo);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Ping request failed");
            return Results.StatusCode(StatusCodes.Status500InternalServerError);
        }
    }
}

方案二:注入ILoggerFactory并创建指定Logger

保持端点方法的参数注入模式,直接注入ILoggerFactory,在方法内部创建针对静态类的Logger:

public static class PingEndpoints
{
    public static void Endpoints(this WebApplication application)
    {
        var group = application.MapGroup("ping");
        group.MapGet("", PingMethod);
    }

    internal static IResult PingMethod([FromServices] ILoggerFactory loggerFactory)
    {
        var logger = loggerFactory.CreateLogger(typeof(PingEndpoints));
        try
        {
            logger.LogInformation("Test log");
            var pingInfo = new PingInfo(DateTime.UtcNow, "Ping successful");
            return Results.Ok(pingInfo);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Ping request failed");
            return Results.StatusCode(StatusCodes.Status500InternalServerError);
        }
    }
}

方案三:将静态类改为非静态类(可选)

如果允许调整类的结构,将静态类改为非静态类,使用构造注入Logger,更符合依赖注入的常规实践:

public class PingEndpoints
{
    private readonly ILogger<PingEndpoints> _logger;

    public PingEndpoints(ILogger<PingEndpoints> logger)
    {
        _logger = logger;
    }

    public void Endpoints(this WebApplication application)
    {
        var group = application.MapGroup("ping");
        group.MapGet("", PingMethod);
    }

    internal IResult PingMethod()
    {
        try
        {
            _logger.LogInformation("Test log");
            var pingInfo = new PingInfo(DateTime.UtcNow, "Ping successful");
            return Results.Ok(pingInfo);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ping request failed");
            return Results.StatusCode(StatusCodes.Status500InternalServerError);
        }
    }
}

对应的Program.cs注册逻辑:

var builder = WebApplication.CreateBuilder(args);

// 注册PingEndpoints为服务
builder.Services.AddTransient<PingEndpoints>();

var app = builder.Build();

// 获取实例并注册端点
var pingEndpoints = app.Services.GetRequiredService<PingEndpoints>();
pingEndpoints.Endpoints(app);

app.Run();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:29:58