Singletons

We just used wired.dataclasses to register a wired factory – in that case, Settings – that was then used later. Let’s do the exact same thing, but with a wired singleton.

Let’s change our Settings to a singleton but changing the factory decorator to singleton:

Everything is the same as in Decorators, Simple Case, we just have different models:

# models.py
from dataclasses import dataclass

from wired.dataclasses import factory, singleton


@singleton()
@dataclass
class Settings:
    """Store some configuration settings for the app"""

    punctuation: str = '.'


@factory()
@dataclass
class Greeter:
    settings: Settings  # Ask DI to get the configured Settings
    name: str = 'Mary'

    def __call__(self, customer):
        punctuation = self.settings.punctuation
        return f'Hello {customer} my name is {self.name}{punctuation}'

And…that’s it, no other changes.