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 153 forks source link

Loosen up locking behavior of GetRegistration #863

Closed dotnetjunkie closed 3 years ago

dotnetjunkie commented 4 years ago

As described in #862, Simple Injector is very strict in locking the Container when calling GetRegistration. The current behavior is to "lock the container in all cases except when an explicitly made registration can be returned." This means that in the following cases, the container will lock:

There are cases where a call to GetRegistration should certainly cause the container to be locked, such as when the underlying code triggers a call to Container.GetInstance, GetService, or GetAllInstances, or BuildExpression. For instance, an unregistered type resolution event might do this.

But for GetRegistration itself, it could itself leave the container unlocked.

Not locking the container has become extra important in v5, because locking the container now, by default, triggers verification. This means that a call to GetRegistration causes the verification, which can be confusing. It also disallows the use of GetRegistration to make decide what and how to register.

Tasks:

dotnetjunkie commented 4 years ago

feature-863 branch created.

dotnetjunkie commented 3 years ago

After doing some more research, I found that the unit tests do a good job in explaining what can happen when GetRegistration does not lock the container:

Whenever a not-explicitly made registration can be returned using unregistered type resolution, the container needs to be locked, changing the container might invalidate the registration. For instance, adding unregistered type resolution events later, might cause a different registration to be returned when GetRegistration is called again.

This means that the locking behavior can't be fully removed. Still, I feel that it's okay to loosen the behavior and only lock when the registration is made implicitly.