ets-labs / python-dependency-injector

Dependency injection framework for Python
https://python-dependency-injector.ets-labs.org/
BSD 3-Clause "New" or "Revised" License
3.89k stars 304 forks source link

Is Resource thread-safe? #713

Open arkadybag opened 1 year ago

arkadybag commented 1 year ago

Hello! Thanks for your library! That is something that i am using in each web app that i created. I really like how things work with this lib but have one question.

Usually, i am using only Factories and Resources, but recently i would need to use Singleton.

I went through documentation about singleton and found one interesting moment:

Singleton provider is NOT thread-safe. You need to explicitly establish a synchronization for using the Singleton provider in the multi-threading application. Otherwise you could trap into the race condition problem: Singleton will create multiple objects.

You suggest to use one of them: ThreadSafeSingleton or ThreadLocalSingleton.

But then i remember that when i started to use Resources i found that:

Resource provider is similar to Singleton. Resource initialization happens only once. You can make injections and use provided instance the same way like you do with any other provider.

So, here is a few questions: 1) Do we need to have Thread-safe Resources or not? 2) If we don't need then why is it a singleton need?

philipbjorge commented 1 year ago

I don't think it is thread safe... https://github.com/ets-labs/python-dependency-injector/blob/cc2304e46e054ae08dc12995428759fbfb51af10/src/dependency_injector/providers.pyx#L3638