I recently started working for an organization that has an enormous code base that uses Autofac as their DI Container of choice.
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 inside their constructors. This is a DI code smell, as injection constructors should be simple.
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.
How would I achieve such a thing? What interception points does Autofac expose that allows this measuring to take place?
With Simple Injector, I'm able to achieve this by registering a resolve interceptor, as shown in this example:
container.Options.RegisterResolveInterceptor((context, producer) =>
{
var watch = Stopwatch.StartNew();
try
{
return producer.Invoke();
}
finally
{
if (watch.TotalElapsedMiliseconds > THRESHOLD)
{
Console.WriteLine(
$"Resolving {context.Registration.ImplementationType} " +
$"took {watch.TotalElapsedMiliseconds} ms.");
}
}
},
c => true);
How to achieve a similar result with Autofac?