Skip to content

Commit 6174e1b

Browse files
authored
Merge pull request #11 from runemalm/feature/next-version
Feature/next version
2 parents 7913b6d + 33c7dcf commit 6174e1b

File tree

15 files changed

+165
-111
lines changed

15 files changed

+165
-111
lines changed

README.md

Lines changed: 34 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0.html)
2-
![First Principles Software](https://img.shields.io/badge/Powered_by-First_Principles_Software-blue)
2+
[![Author: David Runemalm](https://img.shields.io/badge/Author-David%20Runemalm-blue)](https://www.davidrunemalm.com)
33
[![Master workflow](https://github.com/runemalm/py-dependency-injection/actions/workflows/master.yml/badge.svg?branch=master)](https://github.com/runemalm/py-dependency-injection/actions/workflows/master.yml)
4+
[![PyPI version](https://badge.fury.io/py/py-dependency-injection.svg)](https://pypi.org/project/py-dependency-injection/)
5+
![Downloads](https://pepy.tech/badge/py-dependency-injection)
46

57
# py-dependency-injection
68

79
A dependency injection library for Python.
810

11+
## Why py-dependency-injection?
12+
13+
`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+
915
## Features
1016

1117
- **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:
3541
```python
3642
from dependency_injection.container import DependencyContainer
3743

38-
# Define an abstract Connection
39-
class Connection:
40-
pass
44+
# Define an abstract payment gateway interface
45+
class PaymentGateway:
46+
def charge(self, amount: int, currency: str):
47+
raise NotImplementedError()
4148

42-
# Define a specific implementation of the Connection
43-
class PostgresConnection(Connection):
44-
def connect(self):
45-
print("Connecting to PostgreSQL database...")
49+
# A concrete implementation using Stripe
50+
class StripeGateway(PaymentGateway):
51+
def charge(self, amount: int, currency: str):
52+
print(f"Charging {amount} {currency} using Stripe...")
4653

47-
# Define a repository that depends on some type of Connection
48-
class UserRepository:
49-
def __init__(self, connection: Connection):
50-
self._connection = connection
54+
# A service that depends on the payment gateway
55+
class CheckoutService:
56+
def __init__(self, gateway: PaymentGateway):
57+
self._gateway = gateway
5158

52-
def fetch_users(self):
53-
self._connection.connect()
54-
print("Fetching users from the database...")
59+
def checkout(self):
60+
self._gateway.charge(2000, "USD") # e.g. $20.00
5561

56-
# Get an instance of the (default) DependencyContainer
62+
# Get the default dependency container
5763
container = DependencyContainer.get_instance()
5864

59-
# Register the specific connection type as a singleton instance
60-
container.register_singleton(Connection, PostgresConnection)
65+
# Register StripeGateway as a singleton (shared for the app's lifetime)
66+
container.register_singleton(PaymentGateway, StripeGateway)
6167

62-
# Register UserRepository as a transient (new instance every time)
63-
container.register_transient(UserRepository)
68+
# Register CheckoutService as transient (new instance per resolve)
69+
container.register_transient(CheckoutService)
6470

65-
# Resolve an instance of UserRepository, automatically injecting the required Connection
66-
user_repository = container.resolve(UserRepository)
67-
68-
# Use the resolved user_repository to perform an operation
69-
user_repository.find_all()
71+
# Resolve and use the service
72+
checkout = container.resolve(CheckoutService)
73+
checkout.checkout()
7074
```
7175

7276
## Documentation
@@ -81,69 +85,12 @@ For more advanced usage and examples, please visit our [readthedocs](https://py-
8185

8286
You can find the source code for `py-dependency-injection` on [GitHub](https://github.com/runemalm/py-dependency-injection).
8387

84-
## Release Notes
85-
86-
### [1.0.0-beta.2](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-beta.2) (2025-06-09)
87-
88-
- **Enhancement**: Constructor parameters with default values or `Optional[...]` are now supported without requiring explicit registration.
89-
- **Python Version Support**: Added support for Python version 3.13.
90-
91-
### [1.0.0-beta.1](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-beta.1) (2025-01-06)
92-
93-
- **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.
96-
97-
### [1.0.0-alpha.10](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.10) (2024-08-11)
98-
99-
- **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.
100-
101-
### [1.0.0-alpha.9](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.9) (2024-08-08)
102-
103-
- **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.
105-
106-
### [1.0.0-alpha.8](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.8) (2024-06-07)
10788

108-
- **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.
110-
111-
### [1.0.0-alpha.7](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.7) (2024-03-24)
112-
113-
- **Documentation Update**: Updated the documentation to provide clearer instructions and more comprehensive examples.
114-
- **Preparing for Beta Release**: Made necessary adjustments and refinements in preparation for the upcoming first beta release.
115-
116-
### [1.0.0-alpha.6](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.6) (2024-03-23)
117-
118-
- **Factory Registration**: Added support for registering dependencies using factory functions for dynamic instantiation.
119-
- **Instance Registration**: Enabled registering existing instances as dependencies.
120-
- **Tag-based Registration and Resolution**: Introduced the ability to register and resolve dependencies using tags for flexible dependency management.
121-
122-
### [1.0.0-alpha.5](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.5) (2024-03-03)
123-
124-
- **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.
125-
126-
### [1.0.0-alpha.4](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.4) (2024-03-02)
127-
128-
- **Constructor Arguments**: Support for constructor arguments added to dependency registration.
129-
130-
### [1.0.0-alpha.3](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.3) (2024-03-02)
131-
132-
- **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.
134-
135-
### [1.0.0-alpha.2](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.2) (2024-02-27)
89+
## Release Notes
13690

137-
- **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.
91+
### Latest: [1.0.0-beta.3](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-beta.3) (2025-06-14)
14192

142-
### [1.0.0-alpha.1](https://github.com/runemalm/py-dependency-injection/releases/tag/v1.0.0-alpha.1) (2024-02-25)
93+
- **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.
14395

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)

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
version = "1.0"
3636

3737
# The full version, including alpha/beta/rc tags
38-
release = "1.0.0-beta.2"
38+
release = "1.0.0-beta.3"
3939

4040

4141
# -- General configuration ---------------------------------------------------

docs/index.rst

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,25 @@
66
py-dependency-injection
77
=======================
88

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.
1010

11-
Purpose
12-
-------
11+
Overview
12+
--------
1313

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.
1515

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.
1717

1818
Key Advantages
1919
--------------
2020

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>`_.
2428

2529
.. userguide-docs:
2630
.. toctree::

docs/releases.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@
77
Version History
88
###############
99

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+
1017
**1.0.0-beta.2 (2025-06-09)**
1118

1219
- **Enhancement**: Constructor parameters with default values or `Optional[...]` are now supported without requiring explicit registration.

docs/userguide.rst

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ Getting Started
99
Introduction
1010
############
1111

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.
1313

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.
1515

1616
############
1717
Installation
@@ -75,11 +75,11 @@ Basic workflow:
7575
Best Practices
7676
##############
7777

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.
8383

8484
#################
8585
Where to Go Next?

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
setup(
88
name="py-dependency-injection",
9-
version="1.0.0-beta.2",
9+
version="1.0.0-beta.3",
1010
author="David Runemalm, 2025",
1111
author_email="david.runemalm@gmail.com",
1212
description="A dependency injection library for Python.",

src/dependency_injection/container.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,22 @@ def get_args(tp):
3030

3131
class DependencyContainer(metaclass=SingletonMeta):
3232
_default_scope_name: Union[str, Callable[[], str]] = DEFAULT_SCOPE_NAME
33+
_default_container_name: Union[str, Callable[[], str]] = DEFAULT_CONTAINER_NAME
3334

34-
def __init__(self, name: str = None):
35-
self.name = name if name is not None else DEFAULT_CONTAINER_NAME
35+
def __init__(self, name: str):
36+
self.name = name
3637
self._registrations = {}
3738
self._singleton_instances = {}
3839
self._scoped_instances = {}
3940
self._has_resolved = False
4041

42+
@classmethod
43+
def configure_default_container_name(
44+
cls, name_or_callable: Union[str, Callable[[], str]]
45+
) -> None:
46+
"""Override the default container name, which can be string or callable."""
47+
cls._default_container_name = name_or_callable
48+
4149
@classmethod
4250
def configure_default_scope_name(
4351
cls, default_scope_name: Union[str, Callable[[], str]]
@@ -54,7 +62,12 @@ def get_default_scope_name(cls) -> str:
5462

5563
@classmethod
5664
def get_instance(cls, name: str = None) -> Self:
57-
name = name or DEFAULT_CONTAINER_NAME
65+
if name is None:
66+
name = (
67+
cls._default_container_name()
68+
if callable(cls._default_container_name)
69+
else cls._default_container_name
70+
)
5871

5972
if (cls, name) not in cls._instances:
6073
cls._instances[(cls, name)] = cls(name)
@@ -326,3 +339,8 @@ def _unwrap_optional_type(self, annotation: Any) -> Any:
326339

327340
def _should_use_default(self, param_info: inspect.Parameter) -> bool:
328341
return param_info.default is not inspect.Parameter.empty
342+
343+
@classmethod
344+
def clear_instances(cls) -> None:
345+
"""Clear all container instances. Useful for test teardown."""
346+
cls._instances.clear()

tests/unit_test/container/configure/__init__.py

Whitespace-only changes.
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import uuid
2+
from dependency_injection.container import DependencyContainer
3+
from unit_test.unit_test_case import UnitTestCase
4+
5+
6+
class TestConfigureDefaultContainer(UnitTestCase):
7+
def tearDown(self):
8+
# Reset after each test to avoid side effects
9+
DependencyContainer.clear_instances()
10+
DependencyContainer.configure_default_container_name("default_container")
11+
12+
def test_configure_default_container_name_with_static_string(self):
13+
# arrange
14+
DependencyContainer.configure_default_container_name("custom_default")
15+
16+
# act
17+
container = DependencyContainer.get_instance()
18+
19+
# assert
20+
self.assertEqual(container.name, "custom_default")
21+
22+
def test_configure_default_container_name_with_callable(self):
23+
# arrange
24+
container_name = f"test_{uuid.uuid4()}"
25+
DependencyContainer.configure_default_container_name(lambda: container_name)
26+
27+
# act
28+
container = DependencyContainer.get_instance()
29+
30+
# assert
31+
self.assertEqual(container.name, container_name)
32+
33+
def test_get_instance_returns_different_container_when_default_is_changed(self):
34+
# arrange
35+
default_container = DependencyContainer.get_instance()
36+
DependencyContainer.configure_default_container_name("isolated")
37+
isolated_container = DependencyContainer.get_instance()
38+
39+
# assert
40+
self.assertNotEqual(default_container, isolated_container)
41+
self.assertEqual(isolated_container.name, "isolated")
42+
43+
def test_clear_instances_removes_all_containers(self):
44+
# arrange
45+
c1 = DependencyContainer.get_instance("a")
46+
c2 = DependencyContainer.get_instance("b")
47+
48+
# act
49+
DependencyContainer.clear_instances()
50+
51+
# assert
52+
c1_new = DependencyContainer.get_instance("a")
53+
c2_new = DependencyContainer.get_instance("b")
54+
55+
self.assertNotEqual(c1, c1_new)
56+
self.assertNotEqual(c2, c2_new)

tests/unit_test/container/lifecycle/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)