Injector

Python dependency injection framework, inspired by Guice.

Integration

The injector library is a dependency injection framework for python.

You define dependencies of a project as a series of modules and use them to create an Injector instance. Banshee can use this instance to manage dependencies in a handler factory.

Installation

The following CLI command will add the python dependencies to your project.

poetry add banshee[injector]

Example

import banshee
import banshee.extra.injector
import injector

...

class MyModule(injector.Module):
    @injector.singleton
    @injector.provider
    def provide_bus(self, container: injector.Injector) -> banshee.Bus:
        return (
            banshee.Builder()
            .with_middleware(container.get(banshee.IdentityMiddleware))
            .with_middleware(container.get(banshee.CausationMiddleware))
            .with_middleware(container.get(banshee.HandleAfterMiddleware))
            .with_locator(container.get(banshee.HandlerLocator))
            .with_factory(container.get(banshee.HandlerFactory))
            .build()
        )

registry = banshee.Registry()

...

container = injector.Injector((
    banshee.extra.injector.BansheeModule(registry),
    MyModule(),
))

bus = container.get(banshee.Bus)
bus.handle(SomeCommand())

Reference

class banshee.extra.injector.BansheeModule(registry=None)

Bases: Module

Banshee module.

A module to configure default bindings for various banshee related classes.

This module will configure a Bus instance with sensible defaults for local use.

Parameters:

registry (Registry | None) – optional registry to bind

configure(binder)

Override to configure bindings.

Parameters:

binder (Binder) –

Return type:

None

class banshee.extra.injector.InjectorHandlerFactory(container)

Bases: HandlerFactory

Injector handler factory.

This factory will use a pre-configured dependency injection container from the injector module to instantiate handlers.

References are assumed to be functions where the first positional argument of the function is the request, or classes who provide a __call__ method, taking a single positional argument.

Dependencies will be automatically added to the handler, before calling, and can even insert the Bus for recursive calls.

Parameters:

container (Injector) –