Search code examples
autofacasp.net5

Autofac IContainer and DiagnosticTracer for ASP .Net 5


How I can get IContainer instance for my ASP.Net 5 app? I need to enable diagnostics, and based on official documentation SubscribeToDiagnostics method is accessible only from IContainer, and ASP Net Core 3+ Integration this.AutofacContainer = app.ApplicationServices.GetAutofacRoot(); exposes only ILifetimeScope.

I have also noticed that Autofac supports DiagnosticListener - is this a way how I should trace for informations?

Does Autofac provide build in formatters for example for RequestDiagnosticData?

What are your recommendations?


Solution

  • I've updated the ASP.NET Core 3 example for Autofac to show how this works. The secret is using a build callback.

    In your ConfigureContainer method, you register a callback to subscribe to diagnostics.

    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);
        });
    }