dependency-injection.net-4.6benchmarkdotnet

How to use DependencyInjection in BenchmarkDotNet?


I'd like to use BenchmarkDotNet on some legacy code I'm working with right now. It is written in C# Net462. It is a big, old and complex system and I'd like to Benchmark some methods inside some specific class. Those classes use dependency injection and I'm not sure how I could do it. All the examples I've seen so far are not using any dependency injection.

Does anyone have any ideas or examples I could have a look?

Thank you very much.


Solution

  • You need to create the dependency injection container in the ctor or a method with [GlobalSetup] attribute, resolve the type that you want to benchmark and store it in a field. Then use it in a benchmark and dispose the DI container in a [GlobalCleanup] method.

    Pseudocode:

    public class BenchmarksDI
    {
        private IMyInterface _underTest;
        private IDependencyContainer _container;
        
        [GlobalSetup]
        public void Setup()
        {
            _container = CallYourCodeThatBuildsDIContainer();
            _underTest = _container.Resolve<IMyInterface>();
        }
        
        [Benchmark]
        public void MethodA() => _underTest.MethodA();
        
        [GlobalCleanup]
        public void Cleanup() => _container.Dispose();
    }