C# 中的 Worker 服务应用程序 Insights 是否需要在 Worker.cs 中进行 TelemetryClient 依赖注入?

问题描述 投票:0回答:1

我正在尝试为工作人员服务应用程序添加应用程序见解,并按照本文档进行操作。 https://learn.microsoft.com/en-us/azure/azure-monitor/app/worker-service#net-core-worker-service-application 但是我不想添加任何自定义事件,因此我没有在worker.cs中添加TelemetryClient,但现在它不会在门户中记录任何请求。 如果我只是将 TelemetryClient 注入到worker.cs中而不调用任何方法,它就会开始记录所有事件。 有什么方法可以在“AddApplicationInsightsTelemetryWorkerService”方法中初始化此遥测客户端。 我尝试的第二种方法: 我尝试通过调用以下方法来添加 TelemetryClient。

var buildprovider = services.BuildServiceProvider();
TelemetryClient? fooService = provider?.GetService<TelemetryClient>();

但我不想使用 GetService 或调用 buildServiceProvider 因为它可能会创建多个 single 实例。那么还有其他方法可以达到同样的目的吗? 可以使用它而无需注入遥测客户端来获取所有默认请求和依赖项调用吗?

c# dependency-injection azure-application-insights
1个回答
0
投票

ConfigureServices
文件或
Worker.cs
文件(取决于您的项目结构)的
Startup.cs
方法中,您可以添加提供对
TelemetryClient
访问的自定义服务。这可以避免多次调用
BuildServiceProvider

public void ConfigureServices(IServiceCollection services)
{
    // Add Application Insights telemetry
    services.AddApplicationInsightsTelemetryWorkerService(Configuration["ApplicationInsights:InstrumentationKey"]);

    // Add a custom service to provide access to TelemetryClient
    services.AddSingleton(provider =>
    {
        var telemetryClient = provider.GetRequiredService<TelemetryClient>();
        return telemetryClient;
    });
}
  • 下面我通过构造函数注入了
    TelemetryClient
public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly TelemetryClient _telemetryClient;

    public Worker(ILogger<Worker> logger, TelemetryClient telemetryClient)
    {
        _logger = logger;
        _telemetryClient = telemetryClient;
    }

}
  • TelemetryClient
    方法中初始化
    ConfigureServices
    ,无需将其注入到你的worker类中,您可以手动创建和配置
    TelemetryClient
public void ConfigureServices(IServiceCollection services)
{
    // Manual TelemetryClient configuration
    var telemetryConfiguration = new TelemetryConfiguration
    {
        InstrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"],
        // Other configuration settings...
    };

    var telemetryClient = new TelemetryClient(telemetryConfiguration);

    // Add Application Insights telemetry
    services.AddSingleton(telemetryClient);
}
  • 这会在应用程序启动期间初始化
    TelemetryClient
    ,您可以在工作器类中使用依赖注入来访问它。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.