ASP.NET Core 中 UseApplicationInsights/AddApplicationInsights 的简单注入器用法

Simple Injector Usage with UseApplicationInsights/AddApplicationInsights in ASP.NET Core

我正在构建 ASP.NET Core 2.1 应用程序。对于应用程序洞察遥测,我有我的自定义 class,但我也想使用内置的 ITelemetryInitializer。启用自动交叉连接后,Simple Injector 会自动解决这些依赖关系吗?

更新

我尝试了下面的一段代码并得到如下所示的错误。我不确定 Auto Crosswiring 还应该如何工作。

container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IControllerActivator>(
    new SimpleInjectorControllerActivator(container));

services.EnableSimpleInjectorCrossWiring(container);
services.UseSimpleInjectorAspNetRequestScoping(container); 

container.AutoCrossWireAspNetComponents(app);

services.AddApplicationInsightsTelemetry(
    applicationInsightsLoggerConfig.InstrumentationKey);

var test = Container.GetInstance<TelemetryConfiguration>();

The registered delegate for type TelemetryConfiguration threw an exception. The registered delegate for type IServiceScope threw an exception. The IServiceScope is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.'

谢谢

此问题是由 a bug 版本 4.3.0 的 ASP.NET Simple Injector 核心集成包引起的。

由于这个错误,任何 auto 交叉连接的依赖项都可以 在活动范围的上下文中得到解决,即使依赖项是 SingletonTelemetryConfigurationSingleton.

当显式交叉连接该依赖项(即使用 container.CrossWire<TelemetryConfiguration>(app))时,问题就会消失,因为 CrossWire 确实允许 Singletons 在活动范围之外解决。

问题已在集成包patch release 4.3.1中解决。在此版本中,您可以在活动网络请求或简单注入器 Scope 的上下文之外解析 TelemetryConfiguration

但是,如果跨线服务是 TransientScoped,您仍然需要有一个活动的 Web 请求,或者如果 运行后台线程,一个活动的简单注入器 Scope.