ivankorobkov / python-inject

Python dependency injection
Apache License 2.0
672 stars 77 forks source link

thread local instances similar to bind_to_constructor #15

Closed peick closed 8 years ago

peick commented 8 years ago

I'm missing a variant of bind_to_constructor to register thread local instances. bind_to_constructor registers an instance globally for all threads.

bind_to_provider is not suitable in my case, because I don't want to create a different instance of every inject call.

ivankorobkov commented 8 years ago

It is possible to implement thread-local instances with custom providers and then use bind_to_provider. In the provider you can construct an instance exactly once for each thread. For example:


_LOCAL = threading.local()

def my_thread_local_provider():
    if hasattr(_LOCAL, 'instance'):
        return _LOCAL.instance

    _LOCAL.instance = MyObject()
    return _LOCAL.instance
peick commented 8 years ago

You are right. Thank's.