dstanek / snake-guice

A lightweight dependency injection framework for Python
MIT License
7 stars 2 forks source link

Singletons should be scope of the injector #11

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Create an injector to build my instances (somewhere there's a Singleton)
2. Teardown what I'm doing, create a new injector, create new instances

What is the expected output? What do you see instead?

Singleton instances are the same instances across injectors. I would expect 
all singletons created from the same injector to be equal, but singletons 
created from different injectors to be different instances.

What version of the product are you using? On what operating system?

0.2.1dev rev d28d5e34beb6 on Ubuntu 8.10, Python 2.5.2

Please provide any additional information below.

Though a running system should never be strung together by multiple 
injectors, this is a common pattern in tests. In the setup method, create 
an injector with a TestModule, pull out the instances you'd like to test, 
then test them.

This is extraordinarily convenient when dealing with Singletons because 
they hold some state almost by definition. IMHO, one of the big wins of 
using DI is isolated tests without complicated tearDown procedures to reset 
the system's state.

I'm not intimately familiar with the source, but I believe a reasonable way 
to fix this is to attach GuiceData instances to the Injector instead of the 
class. If this sounds reasonable to the author (and he/she agrees this is 
the expected behavior), I'd be more than happy to implement the patch.

I have attached a failing test.

Original issue reported on code.google.com by mark.cha...@gmail.com on 20 Nov 2009 at 4:03

Attachments:

GoogleCodeExporter commented 9 years ago
I'd love to see a patch.

Original comment by tracebac...@gmail.com on 25 Jan 2010 at 2:48

GoogleCodeExporter commented 9 years ago
Here's a viable solution that moves managing scopes for the injector into the 
Binder.
The only change to the exposed scope names is to remove the instantiation of 
the scope classes from the symbol. i.e. scopes.NO_SCOPE, scopes.SINGLETON.

All existing tests pass (i didn't install the web frameworks to check the 
snakeweb test, but looking at the codes shows it ought to still work)

I added some additional tests for this change as well and adjusted the 
cherrypyweb example scopes to match the new pattern.

I also added Mark's test case and it now passes.

Original comment by bill.t...@gmail.com on 29 Jul 2012 at 7:35

Attachments:

GoogleCodeExporter commented 9 years ago
This patch apparently is also another approach for fixing issue 14 as well.

Original comment by bill.t...@gmail.com on 29 Jul 2012 at 7:44