Search code examples
.netioc-containersimple-injector

Can I write the results of SimpleInjectors diagnostics to a log file?


Using SimpleInjector I call container.Verify() at the end of my configuration, and get the diagnostics information in the debugger as described in the documentation. I would like to write that information to a log file. Is there a way access it programmatically or a way hook a logger or tracer into SimpleInjector?


Solution

  • Simple Injector 2.4 contains a diagnostic API (SimpleInjector.Diagnostics.dll) that allow you to query the container for diagnostic warnings. Using this API you can write integration tests that automatically check the configuration for diagnostic warnings:

    // using SimpleInjector.Diagnostics;
    
    [TestMethod]
    public void Container_Always_ContainsNoDiagnosticWarnings()
    {
        // Arrange
        var container = Bootstrapper.GetInitializedContainer();
    
        container.Verify();
    
        // Assert
        var results = Analyzer.Analyze(container);
    
        Assert.IsFalse(results.Any(), Environment.NewLine +
            string.Join(Environment.NewLine,
                from result in results
                select result.Description));
    }
    

    Of course, you can also write this to a file:

    var results = Analyzer.Analyze(container);
    
    File.WriteAllLines("c:\\diagnostic.txt", results.Select(r => r.Description));