title: How to measure and monitor Autofac resolve time of individual components
body: <p>I recently started working for an organization that has an enormous code base that uses Autofac as their DI Container of choice.</p>
  
  <p>Unfortunately, not all developers follow best practices when it comes to writing their classes, which means they sometimes call external services and do other heavy lifting <em>inside</em> their constructors. This is a DI code smell, as <a href="https://blog.ploeh.dk/2011/03/03/InjectionConstructorsshouldbesimple/" rel="nofollow noreferrer">injection constructors should be simple</a>.</p>
  
  <p>Considering the size of the application, and the number of developers working on the code, it is not feasible to review all existing classes one by one. Instead I would like to write an integration test that hooks into the Autofac pipeline and reports resolves that take a considerate amount of time.</p>
  
  <p>How would I achieve such a thing? <strong>What interception points does Autofac expose that allows this measuring to take place?</strong></p>
  
  <p>With Simple Injector, I'm able to achieve this by registering a resolve interceptor, as shown in this example:</p>
  
  <pre><code>container.Options.RegisterResolveInterceptor((context, producer) =&gt;
      {
          var watch = Stopwatch.StartNew();
          try
          {
              return producer.Invoke();
          }
          finally
          {
              if (watch.TotalElapsedMiliseconds &gt; THRESHOLD)
              {
                  Console.WriteLine(
                      $"Resolving {context.Registration.ImplementationType} " +
                      $"took {watch.TotalElapsedMiliseconds} ms.");
              }
          }
      },
      c =&gt; true);
  </code></pre>
  
  <p>How to achieve a similar result with Autofac?</p>