Modular Design with Dependency Injection (DI)
When you need to share logic between controllers, you can use the design pattern of dependency injection (DI). This allows you to create a “service”—a reusable piece of code—that can be injected into controllers, keeping your controller’s routes clean and separating your business logic into single sources of truth.
The Ascender Framework's DI pattern is similar to Angular and NestJS but tailored to Python's design and the simplicity of the framework.
What are Services?
Services are reusable pieces of code that can be injected across your application. They allow you to:
- Define business logic in a centralized manner.
- Share logic seamlessly across controllers and other parts of your application.
- Keep your code organized by separating dependencies and concerns.
Defining a Service
Similar to defining controllers, services follow a structured approach:
- Use the @Injectabledecorator to mark the service as an injectable object. Theprovided_inparameter assigns the service to a specific injection scope (usually"root").
- Define a Python class containing the behavior of the injectable object.
- Optionally, inherit from the Serviceclass for compatibility with older Ascender Framework versions.
Here's the example of AscenderService.
How to Use a Service
To use a service in a controller, follow these steps:
- Import the Service: Import the service into the controller module.
- Inject the Service: Use the controller's __init__method to declare the service as a parameter. The Ascender Framework will automatically resolve the dependency.
Here’s how it might look like in AscenderController
Tip
Read more about Ascender Framework's dependency injection (DI) patterns and use-cases in Dependency Injection Overview