How can I log all resolve requests to Autofac container?

The other answers to this question are good for Autofac up to version 5.x. Anybody looking for an answer to this for Autofac version 6.x should instead look into the built in support for Diagnostics & Logging. Autofac no longer requires custom logic to achieve the kinds of logging requested in this question.

The relevant parts of that are:

  • You no longer have to integrate this into your registration-level logic. Although you can if you wish, there is an example at the linked URL
  • Use a DefaultDiagnosticTracer to coordinate your diagnostics. This is a first-class part of Autofac. You set it up and then have your container subscribe to it.

Here's a minimal example which simply uses Console.WriteLine to log diagnostic content. You should replace that with whatever logging mechanism you wish to use for your app.

var tracer = new DefaultDiagnosticTracer();
tracer.OperationCompleted += (sender, args) =>
{
    Console.WriteLine(args.TraceContent);
};
container.SubscribeToDiagnostics(tracer);

Just to build on an excellent answer by Travis, in case it helps someone in future.

If your class structure is very deep, it may be easier to spot the problematic path, if you display objects in a composition hierarchy. This can be accomplished with somehting like this:

using System;
using System.Text;
using Autofac;
using Autofac.Core;

namespace Tests
{
    public class LogRequestModule : Module
    {
        public int depth = 0;

        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry,
                                                              IComponentRegistration registration)
        {
            registration.Preparing += RegistrationOnPreparing;
            registration.Activating += RegistrationOnActivating;
            base.AttachToComponentRegistration(componentRegistry, registration);
        }

        private string GetPrefix()
        {
            return new string('-',  depth * 2);
        }

        private void RegistrationOnPreparing(object sender, PreparingEventArgs preparingEventArgs)
        {
            Console.WriteLine("{0}Resolving  {1}", GetPrefix(), preparingEventArgs.Component.Activator.LimitType);
            depth++;
        }

        private void RegistrationOnActivating(object sender, ActivatingEventArgs<object> activatingEventArgs)
        {
            depth--;    
            Console.WriteLine("{0}Activating {1}", GetPrefix(), activatingEventArgs.Component.Activator.LimitType);
        }
    }
}

Sample output:

--Resolving  SomeProject.Web.Integration.RestApiAdapter.RestApiAdapter
----Resolving  SomeProject.Web.Integration.RestApiAdapter.Client.ClientFactory
------Resolving  SomeProject.Web.Integration.RestApiAdapter.RestApiAdapterConfiguration
------Activating SomeProject.Web.Integration.RestApiAdapter.RestApiAdapterConfiguration
------Resolving  SomeProject.Web.Integration.RestApiAdapter.Client.Authentication.ApiClientAuthenticationService
--------Resolving  SomeProject.Web.Integration.RestApiAdapter.RestApiAdapterConfiguration
--------Activating SomeProject.Web.Integration.RestApiAdapter.RestApiAdapterConfiguration
------Activating SomeProject.Web.Integration.RestApiAdapter.Client.Authentication.ApiClientAuthenticationService

You can add logging for requests to the container by registering a special module that will catch the Preparing event for all registrations:

public class LogRequestsModule : Module
{
  protected override void AttachToComponentRegistration(
    IComponentRegistry componentRegistry,
    IComponentRegistration registration)
  {
    // Use the event args to log detailed info
    registration.Preparing += (sender, args) =>
      Console.WriteLine(
        "Resolving concrete type {0}",
        args.Component.Activator.LimitType);
  }
}

This is the simplest way to go and will probably get you what you want. Right after a Preparing event logs the information, you'll see the exception pop up and you'll know which component was throwing.

If you want to get fancier, you can set up some event handlers on the container ChildLifetimeScopeBeginning, ResolveOperationBeginning, ResolveOperationEnding, and CurrentScopeEnding events.

  • During ChildLifetimeScopeBeginning you'd need to set up something to automatically attach to any child lifetime ResolveOperationBeginning events.
  • During ResolveOperationBeginning you'd log what is going to be resolved.
  • During ResolveOperationEnding you'd log any exceptions coming out.
  • During CurrentScopeEnding you'd need to unsubscribe from any events on that scope so the garbage collector can clean up the lifetime scope with all of its instances.

The Whitebox profiler project has a module that implements some of this more advanced logging but it's not set up for the latest Autofac so you'd have to use it as a starting point, not a cut/paste sample.

Again, the easiest solution is that module I posted above.