ASP .Net 5 的 Autofac IContainer 和 DiagnosticTracer

Autofac IContainer and DiagnosticTracer for ASP .Net 5

如何为我的 ASP.Net 5 应用获取 IContainer 实例? 我需要启用诊断,并且基于 official documentation SubscribeToDiagnostics method is accessible only from IContainer, and ASP Net Core 3+ Integration this.AutofacContainer = app.ApplicationServices.GetAutofacRoot(); 仅公开 ILifetimeScope.

我还注意到 Autofac 支持 DiagnosticListener - 这是我应该如何追踪信息的方式吗?

Autofac 是否为 RequestDiagnosticData 提供内置格式化程序?

你有什么建议?

我更新了 ASP.NET Core 3 example for Autofac 以展示其工作原理。秘密是使用构建回调。

在您的 ConfigureContainer 方法中,您注册了一个回调以订阅诊断。

public void ConfigureContainer(ContainerBuilder builder)
{
    // Add any Autofac modules or registrations, then...
    //
    // If you want to enable diagnostics, you can do that via a build
    // callback. Diagnostics aren't free, so you shouldn't just do this
    // by default. Note: since you're diagnosing the container you can't
    // ALSO resolve the logger to which the diagnostics get written, so
    // writing directly to the log destination is the way to go.
    var tracer = new DefaultDiagnosticTracer();
    tracer.OperationCompleted += (sender, args) =>
    {
        Console.WriteLine(args.TraceContent);
    };

    builder.RegisterBuildCallback(c =>
    {
        var container = c as IContainer;
        container.SubscribeToDiagnostics(tracer);
    });
}