| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- # -*- coding: utf-8 -*-
- """
- Transient-Scope für Services.
- Erstellt bei jedem Abruf eine neue Instanz.
- """
- from __future__ import annotations
- from typing import Callable, Generic, TypeVar
- from trixy_core.service.scopes.scope import ServiceScope, ScopeType
- T = TypeVar("T")
- class TransientScope(ServiceScope[T], Generic[T]):
- """
- Transient-Scope für Services.
- Jeder Abruf erstellt eine neue Instanz. Keine Instanzen
- werden gecacht.
- Example:
- scope = TransientScope(lambda: MyService())
- instance1 = scope.get_instance("my_service")
- instance2 = scope.get_instance("my_service")
- assert instance1 is not instance2
- """
- scope_type = ScopeType.TRANSIENT
- def __init__(
- self,
- factory: Callable[[], T],
- track_instances: bool = False,
- ) -> None:
- """
- Initialisiert den Transient-Scope.
- Args:
- factory: Factory-Funktion zur Instanz-Erstellung.
- track_instances: Ob erstellte Instanzen getrackt werden sollen.
- """
- super().__init__(factory)
- self._track_instances = track_instances
- self._instances: list[T] = []
- self._instance_count = 0
- @property
- def instance_count(self) -> int:
- """Anzahl der erstellten Instanzen."""
- return self._instance_count
- def get_instance(self, key: str) -> T:
- """
- Erstellt eine neue Instanz.
- Args:
- key: Service-Schlüssel (wird nicht verwendet).
- Returns:
- Neue Service-Instanz.
- """
- instance = self._factory()
- self._instance_count += 1
- if self._track_instances:
- self._instances.append(instance)
- return instance
- def dispose(self) -> None:
- """Disposed alle getrackten Instanzen."""
- for instance in self._instances:
- if hasattr(instance, "dispose"):
- try:
- instance.dispose()
- except Exception:
- pass
- elif hasattr(instance, "close"):
- try:
- instance.close()
- except Exception:
- pass
- self._instances.clear()
- def get_tracked_instances(self) -> list[T]:
- """
- Gibt alle getrackten Instanzen zurück.
- Returns:
- Liste der Instanzen (leer wenn tracking deaktiviert).
- """
- return list(self._instances)
|