服务启动期间如何阅读应用程序见解关键

问题描述

例如,配置ApplicationInsights工具密钥的正确方法是什么,以便可以在服务启动期间使用它(在IConfiguration可用之前)

public class Program
    {
        public static void Main(string[] args)
        {
            var appInsightsTelemetryConfiguration = TelemetryConfiguration.CreateDefault();

            //Todo: how to extract this key from config??
            appInsightsTelemetryConfiguration.InstrumentationKey = "I want to pull this key from config";

            Log.Logger = new LoggerConfiguration()
                    .Enrich.FromLogContext()
                    .Writeto.Console()
                    .Writeto.ApplicationInsights(appInsightsTelemetryConfiguration,TelemetryConverter.Traces)
                    .CreateLogger();

            try
            {
                Log.@R_891_4045@ion(Constants.Logging.Messages.SERVICE_STARTED,assembly.Name);
                CreateHostBuilder(args).Build().Run();
                return;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex,Constants.Logging.Messages.SERVICE_STARTED,assembly.Name);
                return;
            }
            finally
            {
                // make sure all batched messages are written.
                Log.CloseAndFlush();
            }
        }

解决方法

您可以使用以下代码:

    public static void Main(string[] args)
    {
        var appInsightsTelemetryConfiguration = TelemetryConfiguration.CreateDefault();

        //TODO: how to extract this key from config??
        //appInsightsTelemetryConfiguration.InstrumentationKey = "I want to pull this key from config";

        //use this code:
        var builder = new ConfigurationBuilder()
            .AddJsonFile($"appsettings.json",true,true)
            .AddEnvironmentVariables();

        var configuration = builder.Build();

        string myikey = configuration.GetSection("ApplicationInsights:InstrumentationKey").Value;
        appInsightsTelemetryConfiguration.InstrumentationKey = myikey;

        Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.ApplicationInsights(appInsightsTelemetryConfiguration,TelemetryConverter.Traces)
                .CreateLogger();


       //other code

    }