c# - ASP.NET Core 中 UseApplicationInsights/AddApplicationInsights 的简单注入(inject)器用法

标签 c# asp.net-core dependency-injection simple-injector

我正在构建一个 ASP.NET Core 2.1 应用程序。对于应用程序洞察遥测,我有自定义类,但我也想使用内置的 ITelemetryInitializer。当启用自动交叉连接时,简单注入(inject)器是否会自动解决这些依赖关系?

更新

我尝试了下面的代码并得到了如下所示的错误。我不确定自动交叉接线应该如何工作。

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 引起的在简单注入(inject)器的 ASP.NET Core 集成包 4.3.0 版本中。

由于该错误,任何自动跨线依赖关系只能在事件作用域的上下文中解析,即使该依赖关系是 SingletonTelemetryConfigurationSingleton .

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

问题已在 patch release 4.3.1 中解决的集成包。在此版本中,您可以解析TelemetryConfiguration在事件 Web 请求或简单注入(inject)器的上下文之外 Scope

但是,如果跨线服务是 TransientScoped ,您仍然需要有一个事件的 Web 请求,或者,如果在后台线程上运行,则需要一个事件的简单注入(inject)器 Scope .

关于c# - ASP.NET Core 中 UseApplicationInsights/AddApplicationInsights 的简单注入(inject)器用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201919/

相关文章:

c# - VS 告诉我添加对一个看似无关的程序集的引用。如何找出原因?

c# - 使用 ASP.NET Core Web API 在 Swashbuckle 6 (Swagger) 中重命名模型

具有共享首选项的 Flutter 依赖注入(inject)

java - 多语言组件/类 [OOP/Patterns/IoC/DI]

asp.net-mvc-3 - 使用 MVC 3 依赖注入(inject)和 Ninject 2.2 将全局操作过滤器绑定(bind)到区域中的所有 Controller

c# - 检测是否从已发布的独立可执行文件运行

c# - 具有通用集合参数的方法

c# - 如何将插入符号位置设置为 WPF 密码框中的特定索引

c# - 包管理器控制台如何知道要使用哪个连接字符串?

javascript - .Net core - Ajax post不将变量传递给 Controller ​​方法