Skip to main content

Python dependency injection library for your projects or for dependency injection in Django!!

Project description

Injector API

The Injector API is a lightweight dependency injection library designed to simplify the management of dependencies in Python projects.

Prerequisites

  • Python 3.7 or higher
  • A proper environment (virtualenv or conda recommended)

Installation

To install the Injector API, simply run the following pip command:


pip install injector-api

Usage

Configuration injectorConfig.json

After installation, configure the library to suit your project by creating an injectorConfig.json at the project's root. This file should define the following variable:


{
    "MODULE_APPLICATION": "your_directory_name_here"
}

Replace your_directory_name_here with the name of the directory where your module.py resides.

Defining and Registering Dependencies in module.py

The module.py file plays a pivotal role in the Injector API library structure. Here, you define and register the dependencies you wish to inject into your application.

Dependency Registration

To register dependencies, first import the container from the library. Then, use the register method. This method takes the interface you wish to implement and its concrete implementation as arguments.


from injector_api.container import container
# absolute routes, DO NOT USE RELATIVE ROUTES
from aplicacion.src.interfaces import IExampleService
from aplicacion.src.interfaces import ExampleServiceImpl1
from aplicacion.src.interfaces import ExampleServiceImpl2
from aplicacion.src.interfaces import InterfaceWithoutOtherService

Your interfaces and classes here

container.register(IExampleService, ExampleServiceImpl1, override=True) container.register(IExampleService, ExampleServiceImpl2, override=True) container.register(InterfaceWithoutOtherService, ImplInterface, override=True)

or
from injector_api.container import container # absolute routes, DO NOT USE RELATIVE ROUTES from aplicacion.src.interfaces import IExampleService

Your interfaces and classes here

container.register(IExampleService, implementation_name='ExampleServiceImpl1', override=True) container.register(IExampleService, implementation_name='ExampleServiceImpl2', override=True) container.register(InterfaceWithoutOtherService, implementation_name='ImplInterface')

Override Explanation

The override parameter is optional and its default value is False. If set to True, it allows a new registration to replace an existing one for the specified interface. This is useful when you want to change the implementation for an interface without removing the previous registration manually.

Injecting into Functions and Methods

With dependencies registered in module.py, you can utilize the @inject decorator to inject these dependencies into functions or methods.


from injector_api.dynamically import inject

""" Always use the decorator with () - using only @inject will throw an error. For correct usage, employ @inject(). When defining multiple services for an interface, use the format {interface:0}, where 0 corresponds to the first registered injection. """

@inject({IExampleService: 0}) def some_function(service: IExampleService): return service.do_something()

@inject() def some_function_two(service: InterfaceWithoutOtherService): return service.do_something()

In the example above, the IExampleService dependency will be injected into some_function, granting access to its methods and properties.

Location of module.py

Ensure the module.py file is located in the directory you've specified in injectorConfig.json. This file will be automatically read by the library during execution to load and manage dependencies.

Usage with Django

If you're integrating the Injector API within a Django project, you have the option to use the ScopeMiddleware to manage scoped dependencies. This middleware ensures that dependencies with a "scoped" lifecycle are correctly managed within the context of a web request.

However, do note that using scoped dependencies requires your Django application to run in a server mode where each request is handled by a separate thread or process (e.g., using gunicorn with threaded workers). Using scoped dependencies in a single-threaded server (like Django's default development server) might lead to unexpected behaviors.

To use the middleware, add it to your Django project's middleware list:


MIDDLEWARE = [
    ...
    'path_to_your_library.ScopeMiddleware',
    ...
]

Security Recommendations

While the Injector API simplifies dependency management, there are potential security risks when using dynamic loading. We recommend the following precautions:

  • Always validate dynamically loaded information or modules.
  • Avoid loading modules from locations that can be manipulated by untrusted users.
  • Use a secure, isolated environment for your application.
  • Keep the library and all its dependencies up to date.
  • If you're using the optional ScopeMiddleware in Django, ensure your server is configured correctly for scoped dependencies.

Contribute

Contributions are welcome! Please submit pull requests or open issues on our GitHub repository.

License

This library is licensed under the MIT License. See the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

injector_api-0.1.0.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

injector_api-0.1.0-py3-none-any.whl (10.9 kB view details)

Uploaded Python 3

File details

Details for the file injector_api-0.1.0.tar.gz.

File metadata

  • Download URL: injector_api-0.1.0.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for injector_api-0.1.0.tar.gz
Algorithm Hash digest
SHA256 83e6bccf8aabb27f7305d4d9302dbe2449cbb53121e924ae825b9f2b4a1cf805
MD5 51a918446431adaf2d5f705a67509b93
BLAKE2b-256 22c28ad72424eea13272561168ad23521dd767cdb5fd4111caea82d7ea3ceab6

See more details on using hashes here.

File details

Details for the file injector_api-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: injector_api-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 10.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for injector_api-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0439a637bf889c5bfbb18cfba637c58611317d585469618860d934b97491f87f
MD5 468e28511cd5e81f206a56246e46137e
BLAKE2b-256 1c648759d25fb54e5897d853ae161d23fb57a422955bfc464a9835cafdd85e78

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page