如何在 Azure Function 中为 TelemetryConfiguration 使用依赖注入 [英] How to use dependency inject for TelemetryConfiguration in Azure Function

查看:15
本文介绍了如何在 Azure Function 中为 TelemetryConfiguration 使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 Azure Functions 中使用依赖注入进行 TelemetryConfiguration.在我的函数中,当我在函数构造函数中注入 TelemetryConfiguration 时,我将解决它.我想我真的不明白我将如何在 StartUp 中使用 TelemetryConfiguration,这就是我得到异常的原因.我将如何添加我已经配置的 TelemetryConfiguration.

I try to use Dependency injection in Azure Functions for TelemetryConfiguration. In my function I will have it resolved when I inject TelemetryConfiguration in the functions constructor. I suppose I don't really understand how I will do with TelemetryConfiguration in StartUp, thats why I get an exception. How will I add the TelemetryConfiguration I already configured.

到目前为止,我在这里做了一个简单的例子.

I have did an easy example here what I'm doing so far.

[assembly: FunctionsStartup(typeof(StartUp))]
public class StartUp : FunctionsStartup
{
    private string OmsModule { get; } = "OMS.VA";

    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.Configure<TelemetryConfiguration>(
            (o) =>
            {
                o.InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
                o.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
            });
    }
}

public class StopPlaceUpdateTimerTrigger
{
    private TelemetryClient _telemetryClient;
    private string _azureWebJobsStorage;

    public StopPlaceUpdateTimerTrigger(TelemetryConfiguration telemetryConfiguration)
    {
        _telemetryClient = new TelemetryClient(telemetryConfiguration);
    }

    [FunctionName("StopPlaceLoader")]
    public async Task StopPlaceLoaderMain([TimerTrigger("%CRON_EXPRESSION%", RunOnStartup = true)]TimerInfo myTimerInfo, ILogger log, ExecutionContext context)
    {
        SetConfig(context);
        var cloudTable = await GetCloudTableAsync();
        if (cloudTable == null)
        {
            //Do nothing
        }
        //Do nothing
    }

    private async Task<CloudTable> GetCloudTableAsync()
    {
        var storageAccount = CloudStorageAccount.Parse(_azureWebJobsStorage);
        var tableClient = storageAccount.CreateCloudTableClient();
        var table = tableClient.GetTableReference(nameof(StopPlaceLoaderCacheRecord));

        if (!await table.ExistsAsync())
        {
            await table.CreateIfNotExistsAsync();
        }
        return table;
    }

    private void SetConfig(ExecutionContext context)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(context.FunctionAppDirectory)
            .AddJsonFile("local.settings.json", optional: true)
            .AddEnvironmentVariables()
            .Build();
        _azureWebJobsStorage = config["AzureWebJobsStorage"];
    }
}


//local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol...",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"EnableMSDeployAppOffline": "True",
    "CRON_EXPRESSION": "0 */5 22-3 * * *",
"APPINSIGHTS_INSTRUMENTATIONKEY": "..."
  }
}

我得到以下异常;Microsoft.Extensions.DependencyInjection.Abstractions:尝试激活OMS.VA.RealTime.StopPlaceLoader.StopPlaceUpdateTimerTrigger"时,无法解析Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration"类型的服务.

I get the following Exception; Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration' while attempting to activate 'OMS.VA.RealTime.StopPlaceLoader.StopPlaceUpdateTimerTrigger'.

推荐答案

更新:

我们可以将这行代码 var newConfig = TelemetryConfiguration.Active; 改为 var newConfig = TelemetryConfiguration.CreateDefault(); ,因为 TelemetryConfiguration.Active 已弃用.

We can change this line of code var newConfig = TelemetryConfiguration.Active; to var newConfig = TelemetryConfiguration.CreateDefault(); , since TelemetryConfiguration.Active is deprecated.

请使用下面的代码进行 TelemetryConfiguration DI,我使用 blob 触发功能对其进行了测试,效果很好:

Please use the code below for TelemetryConfiguration DI, I test it with a blob trigger function and works well:

using System.IO;
using System.Linq;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

[assembly: WebJobsStartup(typeof(FunctionApp17.MyStartup))]
namespace FunctionApp17
{

    public class MyStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            var configDescriptor = builder.Services.SingleOrDefault(tc => tc.ServiceType == typeof(TelemetryConfiguration));
            if (configDescriptor?.ImplementationFactory != null)
            {
                var implFactory = configDescriptor.ImplementationFactory;
                builder.Services.Remove(configDescriptor);
                builder.Services.AddSingleton(provider =>
                {
                    if (implFactory.Invoke(provider) is TelemetryConfiguration config)
                    {
                        var newConfig = TelemetryConfiguration.Active;
                        newConfig.ApplicationIdProvider = config.ApplicationIdProvider;
                        newConfig.InstrumentationKey = config.InstrumentationKey;

                        return newConfig;
                    }
                    return null;
                });
            }
        }
    }

    public class Function1
    {
        private TelemetryClient _telemetryClient;

        public Function1(TelemetryConfiguration telemetryConfiguration)
        {
            _telemetryClient = new TelemetryClient(telemetryConfiguration);
        }

        [FunctionName("Function1")]
        public void Run([BlobTrigger("samples-workitems/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, ILogger log)
        {
            log.LogInformation($"!!!!!!!!!! C# Blob trigger function Processed blob
 Name:{name} 
 Size: {myBlob.Length} Bytes");
            _telemetryClient.TrackTrace("this is a test message from DI of telemetry client !!!!!!!!!!!!!!");
        }
    }
}

测试结果如下,我可以在azure portal的应用洞察中看到日志:

the test result as below, I can see the logs in the application insights in azure portal:

还有一件事,我看到您尝试在代码中使用 ITelemetry Initializer.您可以按照 GitHub 问题 为您的 ITelemetry Initializercode> 或 Itememetry 处理器

And one more thing, I see you try to use ITelemetry Initializer in your code. You can follow this GitHub issue for your ITelemetry Initializer or Itelemetry Processor

这篇关于如何在 Azure Function 中为 TelemetryConfiguration 使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆