simpleinjector / SimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.
https://simpleinjector.org
MIT License
1.21k stars 155 forks source link

Mass instantiation problem, inadequate setup? #913

Closed vvolkgang closed 3 years ago

vvolkgang commented 3 years ago

Hi,

Having this issue and wondering if it's a problem with the setup or a possible bug.

Mobile app, using reflection / linq auto-registration as explained in the docs. I'm using SimpleInjector to register ViewModels and Services, ViewModels (Transient) use Services (singlethons), services don't use ViewModels.

Problem

The first time we do a GetInstance of a ViewModel that receives X amount of services, ViewModels that use the same services are instantiated as well, regardless of the ViewModels being Transient or Singlethon.

Expected Behaviour

GetInstance of a ViewModel should only instanciate that object and it's dependencies, not the other ViewModels that use the same dependencies.

Is this by design or is my setup missing something?

dotnetjunkie commented 3 years ago

That's probably because Auto Verification is still enabled. For more information, see the documentation.

vvolkgang commented 3 years ago

Was missing that, thanks! That being said, running Container.Verify() (regardless of VerificationOption) triggers the same mass instantiation.

dotnetjunkie commented 3 years ago

running Container.Verify() (regardless of VerificationOption) triggers the same mass instantiation.

Sure. That's what Verify does. It tests if instances can be created.

vvolkgang commented 3 years ago

Got it, will have to turn off AutoVerification!

Was expecting AutoVerification / Verify() process to just check dependencies using reflection, because it would throw away Transient instances. For a mobile scenario verifying slows down the startup (and in my usecase was triggering background initialization processes causing all sorts of unwanted consequences).

Thanks for helping out so quickly!

dotnetjunkie commented 3 years ago

For a mobile scenario verifying slows down the startup

For scenarios where startup performance is crucial, you should prevent verification at startup and move that to an integration test, as mentioned in the documentation.

vvolkgang commented 3 years ago

You're right, missed that!