Suppress unnecessary instantiation with SimpleInjector

1 minute read

.NET has a very lightweight and well-made DI container called SimpleInjector.

I use this a lot, but at that time I was annoyed by the fact that I intended to create an instance once but multiple instances were created. I wanted to do some heavy processing when creating an instance with only one instance generated by the system, but it was actually executed twice.

SimpleInjector is used as follows.

var container = new Container();
container.Register<Foo>();
container.Register<Bar>();
container.Verify();

var foo = container.GetInstance<Foo>();

In SimpleInjector, after registering the dependency, you can verify if there is an object that is not registered in Verify, but in fact, since the instance is created internally at this time, multiple instances as described above The generation is done.

Then, there are the following two problems when it comes to removing Verify.

  1. If you do not verify at the time of development, the discovery of defects will be delayed.
  2. Even if you do not explicitly call Verify, when you getInstance, it will be executed automatically if it is not verified.

Therefore, I think it would be better to implement it as follows.

            var container = new Container();
            container.Register<Foo>();
            container.Register<Bar>();
#if DEBUG
            container.Verify();
#else
            container.Options.EnableAutoVerification = false;
#endif

            var foo = container.GetInstance<Foo>();

Explicitly call Verify when running Debug, otherwise explicitly turn AutoVerification off.

This should avoid unnecessary instantiation for Release-built modules.

As I received in the comments, if the instance to be registered can be registered as a Singleton, I think that it can be avoided even there. Please consider which one is better for you depending on the case.