All Projects → alecthomas → Injector

alecthomas / Injector

Licence: bsd-3-clause
Python dependency injection framework, inspired by Guice

Programming Languages

python
103466 projects - #7 most used programming language

Projects that are alternatives of or similar to Injector

Ulfberht
🗡️ A small but powerful & opinionated DI library. Written in Kotlin, and powered by annotation processing.
Stars: ✭ 234 (-64.06%)
Mutual labels:  dependency-injection, di
inject
[Archived] See https://github.com/goava/di.
Stars: ✭ 49 (-92.47%)
Mutual labels:  dependency-injection, di
Typhoon
Powerful dependency injection for Objective-C ✨✨ (https://PILGRIM.PH is the pure Swift successor to Typhoon!!)✨✨
Stars: ✭ 2,711 (+316.44%)
Mutual labels:  dependency-injection, di
Hiboot
hiboot is a high performance web and cli application framework with dependency injection support
Stars: ✭ 150 (-76.96%)
Mutual labels:  dependency-injection, di
Solid
Книга о принципах объектно-ориентированного дизайна SOLID
Stars: ✭ 280 (-56.99%)
Mutual labels:  dependency-injection, di
Dig
A reflection based dependency injection toolkit for Go.
Stars: ✭ 2,255 (+246.39%)
Mutual labels:  dependency-injection, di
noicejs
extremely thin async dependency injection
Stars: ✭ 16 (-97.54%)
Mutual labels:  dependency-injection, di
Di
psr/container implementation for humans
Stars: ✭ 69 (-89.4%)
Mutual labels:  dependency-injection, di
diod
A very opinionated inversion of control (IoC) container and dependency injector for Typescript, Node.js or browser apps.
Stars: ✭ 36 (-94.47%)
Mutual labels:  dependency-injection, di
lightsaber
Compile time dependency injection framework for JVM languages. Especially for Kotlin.
Stars: ✭ 119 (-81.72%)
Mutual labels:  dependency-injection, di
Di
PSR-11 compatible DI container and injector
Stars: ✭ 141 (-78.34%)
Mutual labels:  dependency-injection, di
Vcontainer
The extra fast, minimum code size, GC-free DI (Dependency Injection) library running on Unity Game Engine.
Stars: ✭ 308 (-52.69%)
Mutual labels:  dependency-injection, di
Deli
Deli is an easy-to-use Dependency Injection(DI).
Stars: ✭ 125 (-80.8%)
Mutual labels:  dependency-injection, di
Ray.di
Guice style dependency injection framework for PHP
Stars: ✭ 175 (-73.12%)
Mutual labels:  dependency-injection, di
Container Ioc
Inversion of Control container & Dependency Injection for Javascript and Node.js apps powered by Typescript.
Stars: ✭ 89 (-86.33%)
Mutual labels:  dependency-injection, di
definject
Unobtrusive Dependency Injector for Elixir
Stars: ✭ 46 (-92.93%)
Mutual labels:  dependency-injection, di
Mydi
moved to https://github.com/cekta/di
Stars: ✭ 21 (-96.77%)
Mutual labels:  dependency-injection, di
Singularity
A extremely fast ioc container for high performance applications
Stars: ✭ 63 (-90.32%)
Mutual labels:  dependency-injection, di
di
🛠 A full-featured dependency injection container for go programming language.
Stars: ✭ 156 (-76.04%)
Mutual labels:  dependency-injection, di
Ditranquillity
Dependency injection for iOS (Swift)
Stars: ✭ 317 (-51.31%)
Mutual labels:  dependency-injection, di

Injector - Python dependency injection framework, inspired by Guice

image Coverage Status

Introduction

While dependency injection is easy to do in Python due to its support for keyword arguments, the ease with which objects can be mocked and its dynamic nature, a framework for assisting in this process can remove a lot of boiler-plate from larger applications. That's where Injector can help. It automatically and transitively provides dependencies for you. As an added benefit, Injector encourages nicely compartmentalised code through the use of :ref:modules <module>.

If you're not sure what dependency injection is or you'd like to learn more about it see:

The core values of Injector are:

  • Simplicity - while being inspired by Guice, Injector does not slavishly replicate its API. Providing a Pythonic API trumps faithfulness. Additionally some features are omitted because supporting them would be cumbersome and introduce a little bit too much "magic" (member injection, method injection).

    Connected to this, Injector tries to be as nonintrusive as possible. For example while you may declare a class' constructor to expect some injectable parameters, the class' constructor remains a standard constructor – you may instantiate the class just the same manually, if you want.

  • No global state – you can have as many Injector instances as you like, each with a different configuration and each with different objects in different scopes. Code like this won't work for this very reason:

      class MyClass:
          @inject
          def __init__(t: SomeType):
              # ...
    
      MyClass()
    

    This is simply because there's no global Injector to use. You need to be explicit and use Injector.get, Injector.create_object or inject MyClass into the place that needs it.

  • Cooperation with static type checking infrastructure – the API provides as much static type safety as possible and only breaks it where there's no other option. For example the Injector.get method is typed such that injector.get(SomeType) is statically declared to return an instance of SomeType, therefore making it possible for tools such as mypy to type-check correctly the code using it.

  • The client code only knows about dependency injection to the extent it needs –  inject, Inject and NoInject are simple markers that don't really do anything on their own and your code can run just fine without Injector orchestrating things.

How to get Injector?

Injector works with CPython 3.6+ and PyPy 3 implementing Python 3.6+.

A Quick Example

>>> from injector import Injector, inject
>>> class Inner:
...     def __init__(self):
...         self.forty_two = 42
...
>>> class Outer:
...     @inject
...     def __init__(self, inner: Inner):
...         self.inner = inner
...
>>> injector = Injector()
>>> outer = injector.get(Outer)
>>> outer.inner.forty_two
42

Or with dataclasses if you like:

from dataclasses import dataclass
from injector import Injector, inject
class Inner:
    def __init__(self):
        self.forty_two = 42

@inject
@dataclass
class Outer:
    inner: Inner

injector = Injector()
outer = injector.get(Outer)
print(outer.inner.forty_two)  # Prints 42

A Full Example

Here's a full example to give you a taste of how Injector works:

>>> from injector import Module, provider, Injector, inject, singleton

We'll use an in-memory SQLite database for our example:

>>> import sqlite3

And make up an imaginary RequestHandler class that uses the SQLite connection:

>>> class RequestHandler:
...   @inject
...   def __init__(self, db: sqlite3.Connection):
...     self._db = db
...
...   def get(self):
...     cursor = self._db.cursor()
...     cursor.execute('SELECT key, value FROM data ORDER by key')
...     return cursor.fetchall()

Next, for the sake of the example, we'll create a configuration type:

>>> class Configuration:
...     def __init__(self, connection_string):
...         self.connection_string = connection_string

Next, we bind the configuration to the injector, using a module:

>>> def configure_for_testing(binder):
...     configuration = Configuration(':memory:')
...     binder.bind(Configuration, to=configuration, scope=singleton)

Next we create a module that initialises the DB. It depends on the configuration provided by the above module to create a new DB connection, then populates it with some dummy data, and provides a Connection object:

>>> class DatabaseModule(Module):
...   @singleton
...   @provider
...   def provide_sqlite_connection(self, configuration: Configuration) -> sqlite3.Connection:
...     conn = sqlite3.connect(configuration.connection_string)
...     cursor = conn.cursor()
...     cursor.execute('CREATE TABLE IF NOT EXISTS data (key PRIMARY KEY, value)')
...     cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")')
...     return conn

(Note how we have decoupled configuration from our database initialisation code.)

Finally, we initialise an Injector and use it to instantiate a RequestHandler instance. This first transitively constructs a sqlite3.Connection object, and the Configuration dictionary that it in turn requires, then instantiates our RequestHandler:

>>> injector = Injector([configure_for_testing, DatabaseModule()])
>>> handler = injector.get(RequestHandler)
>>> tuple(map(str, handler.get()[0]))  # py3/py2 compatibility hack
('hello', 'world')

We can also verify that our Configuration and SQLite connections are indeed singletons within the Injector:

>>> injector.get(Configuration) is injector.get(Configuration)
True
>>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection)
True

You're probably thinking something like: "this is a large amount of work just to give me a database connection", and you are correct; dependency injection is typically not that useful for smaller projects. It comes into its own on large projects where the up-front effort pays for itself in two ways:

  1. Forces decoupling. In our example, this is illustrated by decoupling our configuration and database configuration.
  2. After a type is configured, it can be injected anywhere with no additional effort. Simply @inject and it appears. We don't really illustrate that here, but you can imagine adding an arbitrary number of RequestHandler subclasses, all of which will automatically have a DB connection provided.

Footnote

This framework is similar to snake-guice, but aims for simplification.

© Copyright 2010-2013 to Alec Thomas, under the BSD license

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected]