【问题标题】:How to access the TelemetryClient singleton instance in startup for ASP.NET core app如何在 ASP.NET 核心应用程序的启动中访问 TelemetryClient 单例实例
【发布时间】:2020-02-07 14:46:00
【问题描述】:

我有一个使用 Application Insights 进行遥测的 ASP.NET Core Web 应用程序。我想用我自己的接口包装 TelemetryClient 对象并将该实例添加到服务集合中。为此,我需要访问 startup.cs 中 Telemetry 客户端的单例实例。我可以使用此代码获取服务信息:

        var info = services.Where(x => x.ServiceType.Name == "TelemetryClient").Single();

该信息有一个我希望在其中找到实例的 ImplementationInstance,但它为空。有没有办法获得这个项目的单例实例,以便我可以用它创建我的包装类实例?我的另一个选择是在我的控制器构造函数中创建包装类,因为我可以通过以下代码从服务容器访问它:

HttpContext.RequestServices.GetService(typeof(T)) as T;

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: asp.net-core dependency-injection azure-application-insights


    【解决方案1】:

    你不能这样做吗?

    public class Wrapper
    {
        public Wrapper(TelemetryClient telemetryClient)
        {
             // Handle init
        }
    }
    

    并在服务集合中注册:

    services.AddTransient<Wrapper>();
    

    然后您可以通过构造函数在控制器中获取 Wrapper。

    如果这对您不起作用,请发表评论并解释原因。

    【讨论】:

    • 谢谢。我做了类似的事情。我围绕具有接口和实现的 TelemetryClient 创建了一个包装器。实现类将 TelemetryClient 作为构造函数。接口是 IAppTelemetry,实现是 AppTelemetry。我用这个注册实例: services.AddSingleton();
    猜你喜欢
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2016-10-14
    • 2011-07-15
    • 2017-04-13
    • 2010-09-19
    • 2018-04-22
    • 2016-07-07
    相关资源
    最近更新 更多