4

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.

cicerosf
  • 75
  • 8
  • 1
    Your question is currently too broad. Can you provide us with some examples of where you're stuck, explain what you tried, and what prevents you from benchmarking that code? – Steven Jul 31 '22 at 10:54
  • 1
    Hi @Steven. Thank you for your message. Yes, you are right. it could have had more details. I will elaborate it better my question as soon as I get some time. – cicerosf Aug 01 '22 at 11:50

1 Answers1

9

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();
}
Adam Sitnik
  • 1,256
  • 11
  • 15