Simple
This is the simplest usage of wired
.
The store has one Greeter
who always gives one kind of greeting.
The Greeter is a “singleton”: there is only one, and we create it at startup time and re-use for the lifetime of the application.
Whenever a customer comes in, we make a “container” to do the work of the interaction.
We use the container to get from the registry all the pieces needed.
(In this case, the only thing we need is the Greeter
.)
In this application, main
shows:
Wiring everything into a registry
Later (and repeatedly), processing an interaction to greet a customer
This stuff in main
would be the framework-y parts of your application.
Meaning, your application is responsible for making a registry, making a container, and “doing your thing” (greet a customer, process an HTTP request) within that container.
Code
"""
A customer walks into a store. Do the steps to interact with them:
- Get *the* (not *a*) greeter
- Interact with them
Very simple wired application:
- Registry
- Singleton that says hello
"""
from dataclasses import dataclass
from wired import ServiceRegistry
@dataclass
class Greeter:
greeting: str
def __call__(self) -> str:
return f'{self.greeting} !!'
def setup() -> ServiceRegistry:
# Make the registry
registry = ServiceRegistry()
# Make the greeter
greeter = Greeter(greeting='Hello')
# Register it as a singleton using its class for the "key"
registry.register_singleton(greeter, Greeter)
return registry
def greet_a_customer(registry: ServiceRegistry) -> str:
# A customer comes in, handle the steps in the greeting
# as a container.
container = registry.create_container()
# First step in the interaction: get the greeter
the_greeter: Greeter = container.get(Greeter)
# Now do the steps in the interaction
greeting = the_greeter()
return greeting
def main():
registry = setup()
greeting = greet_a_customer(registry)
assert greeting == 'Hello !!'