【问题标题】:Dependency Injection to modules对模块的依赖注入
【发布时间】:2011-09-22 00:56:23
【问题描述】:

考虑一个模块,例如some_module,各种模块在同一个解释器进程中使用。这个模块将有一个单一的上下文。为了使some_module 方法工作,它必须接收一个类实例的依赖注入。

将依赖项注入模块的pythonic和优雅的方式是什么?

【问题讨论】:

    标签: python dependency-injection python-module


    【解决方案1】:

    使用全局模块。

    import some_module
    some_module.classinstance = MyClass()
    

    some_module 可以有代码来设置默认实例(如果没有收到),或者只是将classinstance 设置为None 并检查以确保在调用方法时设置它。

    【讨论】:

      【解决方案2】:

      恕我直言,完全成熟的 Dependency Injection 与所有行话更适合静态类型语言,如 Java,在 python 中你可以很容易地做到这一点,例如这里是一个简单的骨骼 injection

      class DefaultLogger(object):
         def log(self, line):
            print line
      
      _features = {
         'logger': DefaultLogger
         }
      
      def set_feature(name, feature):
         _features[name] = feature
      
      def get_feature(name):
         return _features[name]()
      
      class Whatever(object):
      
         def dosomething(self):
            feature = get_feature('logger')
      
            for i in range(5):
               feature.log("task %s"%i)
      
      if __name__ == "__main__":
         class MyLogger(object):
            def log(sef, line):
               print "Cool",line
      
         set_feature('logger', MyLogger)
      
         Whatever().dosomething()
      

      输出:

      Cool task 0
      Cool task 1
      Cool task 2
      Cool task 3
      Cool task 4
      

      如果您认为缺少某些内容,我们可以轻松地添加它,它的 python。

      【讨论】:

      • 这不是依赖注入,而是服务定位器。
      • @deamon 可能没有,可能两者都是 get_feature('logger') 是服务定位器,但 set_feature 在应用程序开始时注入 MyLogger,这是差异之间的良好联系 martinfowler.com/articles/…
      • 不幸的是,这是一个服务定位器。还有Service Locator is an antipattern
      【解决方案3】:

      您可以使用dependencies package 来实现您的目标。

      【讨论】:

      • 链接好像失效了。
      猜你喜欢
      • 2011-06-02
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多