简体   繁体   English

以 static 方式引用非静态方法

[英]Referencing non-static method in a static way

I have this C# class:我有这个 C# class:

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() is a non-static method in the HHandler class: HHandler.GetHighMark()HHandler class 中的非静态方法:

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

When I run my check I get a HTTP 500 error with the following error in the log:当我运行检查时,我收到HTTP 500错误,日志中出现以下错误:

2021-03-03 11:54:51.308Z ERROR APP=2227 COMP=3789 [13] Connection id "0HM6U7CJEMU0S", Request id "0HM6U7CJEMU0S:00000001": An unhandled exception was thrown by the application. 2021-03-03 11:54:51.308Z 错误 APP=2227 COMP=3789 [13] 连接 ID“0HM6U7CJEMU0S”,请求 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()'. at Ed.Health.HealthCheckHMark.<>c.<<-cctor>b__2_0>d.MoveNext() at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at Ed.Health.HealthCheckHMark.<>c.<.cctor>b__2_0(HttpContext context, HealthReport report) at Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckMiddleware.InvokeAsync(HttpContext httpContext) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)" - Logger=Microsoft.AspNetCore.Server.Kestrel,Level=ERROR,ThreadId=13,,Exception="System.MissingMethodException: 找不到方法:'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 context, HealthReport report) at Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckMiddleware.InvokeAsync(HttpContext httpContext) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger 记录器)在 Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 应用程序)“

I think the issue is that I'm trying to reference a non-static method in a static way.我认为问题在于我试图以 static 方式引用非静态方法。 How do I resolve this though?我该如何解决这个问题?

Additional Info附加信息

Here's my HHandler class:这是我的HHandler class:

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();
    }
}

What are you trying to check in this healthcheck endpoint?您要在此运行状况检查端点中检查什么?

It is ussialy used to check that some existing system is healthy, like internal DB connection is ok, or some resources are below limits etc. So you need to run a check on that existing system - if it's not a sttatic class, than there should be an instance somewhere, singleton maybe, or some way to create that instance (some factory for example), if it's transient.它通常用于检查某些现有系统是否健康,例如内部数据库连接正常,或者某些资源低于限制等。因此,您需要对该现有系统进行检查 - 如果它不是静态 class,则应该是某个地方的一个实例,singleton 也许,或者以某种方式创建该实例(例如某个工厂),如果它是瞬态的。 Usialy a good idea is to ask a DI container to resolve the instance for you.通常一个好主意是让 DI 容器为您解析实例。 Providing that you are using DI of course (well, in a modern AspNetCore I think you should use it:)当然,前提是您使用的是 DI(嗯,在现代 AspNetCore 中,我认为您应该使用它:)

Try something like尝试类似的东西

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

and see if this helps.看看这是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM