You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`py-dependency-injection` is inspired by the built-in dependency injection system in **ASP.NET Core**. It provides a lightweight and extensible way to manage dependencies in Python applications. By promoting constructor injection and supporting scoped lifetimes, it encourages clean architecture and makes testable, maintainable code the default.
14
+
9
15
## Features
10
16
11
17
-**Scoped Registrations:** Define the lifetime of your dependencies as transient, scoped, or singleton.
@@ -35,38 +41,36 @@ Here's a quick example to get you started:
35
41
```python
36
42
from dependency_injection.container import DependencyContainer
37
43
38
-
# Define an abstract Connection
39
-
classConnection:
40
-
pass
44
+
# Define an abstract payment gateway interface
45
+
classPaymentGateway:
46
+
defcharge(self, amount: int, currency: str):
47
+
raiseNotImplementedError()
41
48
42
-
#Define a specific implementation of the Connection
43
-
classPostgresConnection(Connection):
44
-
defconnect(self):
45
-
print("Connecting to PostgreSQL database...")
49
+
#A concrete implementation using Stripe
50
+
classStripeGateway(PaymentGateway):
51
+
defcharge(self, amount: int, currency: str):
52
+
print(f"Charging {amount}{currency} using Stripe...")
46
53
47
-
#Define a repository that depends on some type of Connection
48
-
classUserRepository:
49
-
def__init__(self, connection: Connection):
50
-
self._connection=connection
54
+
#A service that depends on the payment gateway
55
+
classCheckoutService:
56
+
def__init__(self, gateway: PaymentGateway):
57
+
self._gateway=gateway
51
58
52
-
deffetch_users(self):
53
-
self._connection.connect()
54
-
print("Fetching users from the database...")
59
+
defcheckout(self):
60
+
self._gateway.charge(2000, "USD") # e.g. $20.00
55
61
56
-
# Get an instance of the (default) DependencyContainer
62
+
# Get the default dependency container
57
63
container = DependencyContainer.get_instance()
58
64
59
-
# Register the specific connection type as a singleton instance
-**Transition to Beta**: Transitioned from alpha to beta. Features have been stabilized and are ready for broader testing.
94
-
-**Removal**: We have removed the dependency container getter and setter functions, as well as the RegistrationSerializer class, which were first introduced in v1.0.0-alpha.9. This decision reflects our focus on maintaining a streamlined library that emphasizes core functionality. These features, which would not be widely used, added unnecessary complexity without offering significant value. By removing them, we are reinforcing our commitment to our design principles.
95
-
-**Enhancement**: Added suppprt for configuring default scope name. Either a static string value, or a callable that returns the name.
-**Tagged Constructor Injection**: Introduced support for constructor injection using the `Tagged`, `AnyTagged`, and `AllTagged` classes. This allows for seamless injection of dependencies that have been registered with specific tags, enhancing flexibility and control in managing your application's dependencies.
-**Breaking Change**: Removed constructor injection when resolving dataclasses.
104
-
-**Enhancement**: Added dependency container getter and setter for registrations. Also added new `RegistrationSerializer` class for for serializing and deserializing them. These additions provide a more flexible way to interact with the container's registrations.
-**Bug Fix**: Fixed an issue in the dependency resolution logic where registered constructor arguments were not properly merged with automatically injected dependencies. This ensures that constructor arguments specified during registration are correctly combined with dependencies resolved by the container.
109
-
-**Documentation Update**: The documentation structure has been updated for better organization and ease of understanding.
-**Critical Package Integrity Fix**: This release addresses a critical issue that affected the packaging of the Python library in all previous alpha releases (1.0.0-alpha.1 to 1.0.0-alpha.4). The problem involved missing source files in the distribution, rendering the library incomplete and non-functional. Users are strongly advised to upgrade to version 1.0.0-alpha.5 to ensure the correct functioning of the library. All previous alpha releases are affected by this issue.
-**Breaking Change**: Starting from this version, the `@inject` decorator can only be used on static class methods and class methods. It can't be used on instance methods anymore.
133
-
-**Documentation Update**: The documentation has been updated to reflect the new restriction on the usage of the decorator.
-**Python Version Support**: Added support for Python versions 3.7, 3.9, 3.10, 3.11, and 3.12.
138
-
-**New Feature**: Method Injection with Decorator: Introduced a new feature allowing method injection using the @inject decorator. Dependencies can now be injected into an instance method, providing more flexibility in managing dependencies within class instance methods.
139
-
-**New Feature**: Multiple Containers: Enhanced the library to support multiple containers. Users can now create and manage multiple dependency containers, enabling better organization and separation of dependencies for different components or modules.
140
-
-**Documentation Update**: Expanded and improved the documentation to include details about the newly added method injection feature and additional usage examples. Users can refer to the latest documentation at readthedocs for comprehensive guidance.
-**Enhancement**: Added `DependencyContainer.configure_default_container_name(...)` to support container isolation in parallel tests, even when application code uses a single shared container via `DependencyContainer.get_instance()`.
94
+
-**Enhancement**: Added `DependencyContainer.clear_instances()` as a clean alternative to manually resetting `_instances` during test teardown.
143
95
144
-
-**Initial alpha release**.
145
-
-**Added Dependency Container**: The library includes a dependency container for managing object dependencies.
146
-
-**Added Constructor Injection**: Users can leverage constructor injection for cleaner and more modular code.
147
-
-**Added Dependency Scopes**: Define and manage the lifecycle of dependencies with support for different scopes.
148
-
-**Basic Documentation**: An initial set of documentation is provided, giving users an introduction to the library.
149
-
-**License**: Released under the GPL 3 license.
96
+
➡️ Full changelog: [GitHub Releases](https://github.com/runemalm/py-dependency-injection/releases)
Copy file name to clipboardExpand all lines: docs/index.rst
+12-8Lines changed: 12 additions & 8 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,21 +6,25 @@
6
6
py-dependency-injection
7
7
=======================
8
8
9
-
A dependency injection library for Python.
9
+
A dependency injection library for Python — inspired by the built-in DI system in ASP.NET Core.
10
10
11
-
Purpose
12
-
-------
11
+
Overview
12
+
--------
13
13
14
-
Dependency injection is a powerful design pattern that promotes loose coupling and enhances testability in software applications. `py-dependency-injection` is a prototypical implementation of this pattern, designed to provide the essential features needed for effective dependency management in both small scripts and larger software projects.
14
+
`py-dependency-injection` provides a lightweight and extensible way to manage dependencies in Python applications. It promotes constructor injection, supports scoped lifetimes, and encourages clean architecture through explicit configuration and testable design.
15
15
16
-
This library is particularly suited for beginners exploring the concept of dependency injection, as it offers a straightforward and easy-to-understand implementation. It serves as an excellent starting point for learning the pattern and can also be used as a foundational base for frameworks requiring a more specialized interface for dependency injection.
16
+
This library is well-suited for both standalone use in Python applications and as a foundation for frameworks or tools that require structured dependency management.
17
17
18
18
Key Advantages
19
19
--------------
20
20
21
-
- **Suitable for Learning:** Ideal for beginners exploring the concept of dependency injection.
22
-
- **Base Implementation for Frameworks:** Can be used as a foundational base for frameworks requiring a more specialized interface for dependency injection.
23
-
- **Standalone Solution:** Can also be used on its own, as a fully-featured dependency injection solution in any software project.
21
+
- **Familiar model** – Inspired by ASP.NET Core’s DI system
22
+
- **Scoped lifetimes** – Support for `singleton`, `scoped`, and `transient` registrations
23
+
- **Explicit injection** – Promotes clarity over magic
24
+
- **Test-friendly** – Designed for container isolation and overrides
25
+
- **Minimalistic** – Easy to use, extend, and integrate
26
+
27
+
You can find the source code for `py-dependency-injection` in our `GitHub repository <https://github.com/runemalm/py-dependency-injection>`_.
Copy file name to clipboardExpand all lines: docs/releases.rst
+7Lines changed: 7 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -7,6 +7,13 @@
7
7
Version History
8
8
###############
9
9
10
+
**1.0.0-beta.3 (2025-06-14)**
11
+
12
+
- **Enhancement**: Added `DependencyContainer.configure_default_container_name(...)` to support container isolation in parallel tests, even when application code uses a single shared container via `DependencyContainer.get_instance()`.
13
+
- **Enhancement**: Added `DependencyContainer.clear_instances()` as a clean alternative to manually resetting `_instances` during test teardown.
14
+
15
+
`View release on GitHub <https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-beta.3>`_
16
+
10
17
**1.0.0-beta.2 (2025-06-09)**
11
18
12
19
- **Enhancement**: Constructor parameters with default values or `Optional[...]` are now supported without requiring explicit registration.
Copy file name to clipboardExpand all lines: docs/userguide.rst
+7-7Lines changed: 7 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,9 +9,9 @@ Getting Started
9
9
Introduction
10
10
############
11
11
12
-
`py-dependency-injection` is a lightweight and flexible dependency injection library for Python. It simplifies managing dependencies in your applications, promoting cleaner and more testable code.
12
+
`py-dependency-injection` is a lightweight and extensible dependency injection library for Python — inspired by the built-in DI system in **ASP.NET Core**. It promotes constructor injection, supports scoped lifetimes, and encourages clean, testable application architecture.
13
13
14
-
This guide will help you understand the key concepts and how to start using the library. For detailed examples, see the `Examples` section.
14
+
This guide provides an overview of the key concepts and demonstrates how to start using the library effectively. For detailed examples, see the `Examples` section.
15
15
16
16
############
17
17
Installation
@@ -75,11 +75,11 @@ Basic workflow:
75
75
Best Practices
76
76
##############
77
77
78
-
- **Use Constructor Injection**: Preferred for most cases as it promotes clear and testable designs.
79
-
- **Leverage Tags for Organization**: Group dependencies logically using tags.
80
-
- **Choose the Right Scope**: Use scoped or singleton lifetimes to optimize performance and resource usage.
81
-
- **Keep Dependencies Decoupled**: Avoid tightly coupling your components to the container.
82
-
- **Isolate Contexts with Containers**: Use multiple containers to manage dependencies for separate modules or contexts.
78
+
- **Prefer Constructor Injection**: It promotes clear interfaces and testable components.
79
+
- **Use the Right Lifetime**: Choose between transient, scoped, and singleton based on your component's role.
80
+
- **Organize with Tags**: Use tag-based registration and resolution to group related services.
81
+
- **Avoid Container Coupling**: Inject dependencies via constructors rather than accessing the container directly.
82
+
- **Use Multiple Containers When Needed**: For modular apps or test isolation, create dedicated containers.
0 commit comments