Search code examples
c#.net-coredependency-injectionautofac

Validate DI container at startup


I'd like to validate my DI container (aka check if I haven't forgotten to add a DI registration in my Startup class) at the very start of the application. Meaning, once all the services are added, I'd like to try and resolve each one of them so that the application throws an exception if I forgot one.

Naturally, I'd like to do this only in DEBUG mode. For the default NET Core DI container, I can iterate through services and try to resolve them all (as in the case below), but how do I do that through Autofac (preferrably in ConfigureContainer)?

#if DEBUG
    var sp = services.BuildServiceProvider();
    foreach (var item in services)
    {
        _ = sp.GetRequiredService(item.ServiceType);
    }
#endif

Solution

  • Autofac does not offer container registration validation and has no plans to do so in the near future. The issue I linked there explains why, but the long and the short of it is - since so many things can come from lambdas and dynamic code, there's too much that can't be validated. It seemed like the false positives or the "we validated 50% of the container but not the other 50% because it's dynamic" would give people a false sense of security, or, more likely, just make people angry that the results weren't correct. "My container validated but this thing failed! Autofac sucks!"

    On the other hand, Autofac 6.0 introduced a robust diagnostics mechanism for troubleshooting and tracing issues. If you encounter issues, this can make it easier to figure out why.