以静态方式引用非静态方法

时间:2021-03-03 11:59:15

标签: c# .net static-methods

我有这个 C# 类:

public static class HealthCheckHighMark
{

    public static IEndpointConventionBuilder MapHighMarkChecks(
        this IEndpointRouteBuilder endpoints)
    {

        return endpoints.MapHealthChecks("/api/health/highmark", new HealthCheckOptions
        {
            ResponseWriter = async (context, report) =>
            {
                var result = JsonConvert.SerializeObject(
                    new HighMarkResult
                    {
                        HighMark = HHandler.GetHighMark().High.ToString(),
                    }, Formatting.None,
                    new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                context.Response.ContentType = MediaTypeNames.Application.Json;
                await context.Response.WriteAsync(result);
            },

            Predicate = (check) => check.Tags.Contains("highmark")
        });
    }
}

HHandler.GetHighMark()HHandler 类中的非静态方法:

public WatermarkOffsets GetHighMark()
{
    return consumer.QueryWatermarkOffsets(TopicPartition.TopicPartition, TimeSpan.FromSeconds(2));
}

当我运行检查时,我收到一个 HTTP 500 错误,并在日志中显示以下错误:

<块引用>

2021-03-03 11:54:51.308Z ERROR APP=2227 COMP=3789 [13] Connection id "0HM6U7CJEMU0S", Request id "0HM6U7CJEMU0S:00000001": 应用程序抛出了一个未处理的异常。 - Logger=Microsoft.AspNetCore.Server.Kestrel,Level=ERROR,ThreadId=13,,Exception="System.MissingMethodException: Method not found: 'Confluent.Kafka.WatermarkOffsets Ed.Md.FHandler.Health.HHandler.GetHighMark() '。 在 Ed.Health.HealthCheckHMark.<>c.<<-cctor>b__2_0>d.MoveNext() 在 System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) 在 Ed.Health.HealthCheckHMark.<>c.<.cctor>b__2_0(HttpContext 上下文,HealthReport 报告) 在 Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckMiddleware.InvokeAsync(HttpContext httpContext) 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 在 Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 应用程序)"

我认为问题在于我试图以静态方式引用非静态方法。我该如何解决这个问题?

附加信息

这是我的 HHandler 课:

public class HHandler : IHHandler
{
    private readonly IConfig _config;
    public IConsumer<Ignore, MdpMessage> consumer { get;  set; }
    public TopicPartitionOffset TopicPartition { get; set; }

    public HHandler([NotNull] IConfig healthOptions)
    {
        _config = healthOptions;
    }

    public WatermarkOffsets GetHighMark()
    {
        return consumer.QueryWatermarkOffsets(TopicPartition.TopicPartition, TimeSpan.FromSeconds(2));
    }

    WatermarkOffsets IHHandler.GetHighMark()
    {
        return GetHighMark();
    }
}

1 个答案:

答案 0 :(得分:0)

您要在此运行状况检查端点中检查什么?

通常用于检查某些现有系统是否健康,例如内部数据库连接是否正常,或者某些资源低于限制等。 因此,您需要对 那个 现有系统进行检查 - 如果它不是静态类,则应该在某处有一个实例,可能是单例,或者以某种方式创建该实例(例如某个工厂) ,如果它是短暂的。通常,一个好主意是要求 DI 容器为您解析实例。当然,前提是您使用的是 DI(嗯,在现代 AspNetCore 中,我认为您应该使用它 :)

尝试类似的东西

context.RequestServices.GetService(typeof(HHandler)).GetHighMark().High.ToString()

看看这是否有帮助。

相关问题