【问题标题】:How to use dependency injection to inject object into module?如何使用依赖注入将对象注入模块?
【发布时间】:2014-06-25 06:56:59
【问题描述】:

这是我的场景。我有一个包含几个模块的包。它们都从settings.py 导入。但是,某些变量取决于用户输入。

...
# some CONSTANTS
...
PROJECT_DIR = Path(os.path.abspath(__file__)).parent.ancestor(1)
SCRIPT_DIR = PROJECT_DIR.child('scripts')
data_input = DATA_ROOT.child('input')
input_root = data_input.child(options.root_input) # the options object holds some user input

# then use input_root to get an instance of class Countries
from countries import Countries
country_object = Countries(input_root)

有几个模块需要country_object。因此,从settings 导入它们将是最干净的解决方案。

所以我正在阅读dependency injection,我认为这是在这里派上用场的东西。但是我发现很难将其包裹起来,那么如何使用依赖注入将选项对象注入模块?

【问题讨论】:

    标签: python dependency-injection module


    【解决方案1】:

    说到模式,有两种哲学,让你的问题适合模式,让模式适合你的问题。我遵循后者。所以这将是我对dependency injection 模式的改编:

    class UserCountry(object):
         def __init__(self):be populated by user data
             self.Country = None
    
         def set_input_root(self, input_root):
             self.input_root = input_root # <-- this is a list/dict etc that I assume will 
    
         def __call__(self):
             if self.Country:
                 return self.Country
             else:
                 # Select country
                 self.Country = Country
                 return self.Country
    

    settings.py:

     user_country = UserCountries()
    

    input_root 被定义时:

    settings.user_country.set_input_root(input_root) 
    

    在其他模块中:

     settings.user_country() # gives you the Country object
    

    【讨论】:

    • 但是settings.pyinput_root 一无所知。所以我不能从设置中调用UserCountries()。我可以从我的主程序中调用它,但问题仍然存在,因为其他模块也不知道 root_input。
    • 那么 input_root 什么时候设置?
    • @LarsVegas 我更新了我的答案,但你确实意识到在你知道输入根之前你不会知道 input_root...
    • 它取决于用户输入,所以在调用主程序时。但是主程序已经从设置中导入。主程序以外的其他模块也将导入设置。一个模块也可以在主程序之外使用包的另一个模块。所以 input_root 和 country-instance 在主程序执行期间必须是有效的并且可以全局访问。
    • 你看到我的更新版本了吗?只要在需要实际国家/地区之前在主程序中设置set_input_root,就可以了。如果会话是持久的,您可能需要添加默认值并将其保存到数据库中。
    猜你喜欢
    • 2011-09-22
    • 2021-08-04
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多