What is a Pythonic way for Dependency Injection?

后端 未结 9 2154
终归单人心
终归单人心 2020-12-02 06:57

Introduction

For Java, Dependency Injection works as pure OOP, i.e. you provide an interface to be implemented and in your framework code accept an instance of a c

9条回答
  •  没有蜡笔的小新
    2020-12-02 07:48

    After playing around with some of the DI frameworks in python, I've found they have felt a bit clunky to use when comparing how simple it is in other realms such as with .NET Core. This is mostly due to the joining via things like decorators that clutter the code and make it hard to simply add it into or remove it from a project, or joining based on variable names.

    I've recently been working on a dependency injection framework that instead uses typing annotations to do the injection called Simple-Injection. Below is a simple example

    from simple_injection import ServiceCollection
    
    
    class Dependency:
        def hello(self):
            print("Hello from Dependency!")
    
    class Service:
        def __init__(self, dependency: Dependency):
            self._dependency = dependency
    
        def hello(self):
            self._dependency.hello()
    
    collection = ServiceCollection()
    collection.add_transient(Dependency)
    collection.add_transient(Service)
    
    collection.resolve(Service).hello()
    # Outputs: Hello from Dependency!
    

    This library supports service lifetimes and binding services to implementations.

    One of the goals of this library is that it is also easy to add it to an existing application and see how you like it before committing to it as all it requires is your application to have appropriate typings, and then you build the dependency graph at the entry point and run it.

    Hope this helps. For more information, please see

    • github: https://github.com/BradLewis/simple-injection
    • docs: https://simple-injection.readthedocs.io/en/latest/
    • pypi: https://pypi.org/project/simple-injection/

提交回复
热议问题