.netloopsusing

Loop Inside a dotnet using stament


I have this code

public static void AddMeter(List<string> meter)
{
    using MeterProvider meterProvider = Sdk.CreateMeterProviderBuilder()
            .AddMeter("Meter.Errors")
            .AddMeter("Meter.Prompts")
            .AddPrometheusHttpListener(options => options.UriPrefixes = new string[] { "http://*:9184/" })
            .Build();
}

And What I am trying to do is adding meters (.AddMeter()) by iteration.

so something like this;

using MeterProvider meterProvider = Sdk.CreateMeterProviderBuilder()
        foreach (var meter in meters)
        {
            .AddMeter(meter)
        }
        .AddPrometheusHttpListener(options => options.UriPrefixes = new string[] { "http://*:9184/" })
        .Build();

What would be the correct synax for this?


Solution

  • Do you mean something like this?:

    var builder = Sdk.CreateMeterProviderBuilder();
    foreach (var meter in meters)
    {
        builder = builder.AddMeter(meter);
    }
    using MeterProvider meterProvider = builder
        .AddPrometheusHttpListener(options => options.UriPrefixes = new string[] { "http://*:9184/" })
        .Build();
    

    Basically you just store the result of Sdk.CreateMeterProviderBuilder() in a variable, call .AddMeter() in a loop updating that variable, and then call the rest of what you need on the result of that variable. There's nothing particularly special about the syntax of a fluid API like this, each method is simply returning the same updated object which can be stored in a variable like any other.