跳转至

diagnose_container

symphra_container.visualization.diagnose_container(container)

诊断容器健康状态.

检查循环依赖、无法解析的服务等问题。

参数:

名称 类型 描述 默认
container Container

容器实例

必需

返回:

类型 描述
ContainerDiagnostic

诊断报告

Example

report = diagnose_container(container) print(f"Health Score: {report.health_score}/100") if report.circular_dependencies: ... print("Circular dependencies found!") if report.warnings: ... for warning in report.warnings: ... print(f"⚠️ {warning}")

源代码位于: src/symphra_container/visualization.py
def diagnose_container(container: Container) -> ContainerDiagnostic:
    """诊断容器健康状态.

    检查循环依赖、无法解析的服务等问题。

    Args:
        container: 容器实例

    Returns:
        诊断报告

    Example:
        >>> report = diagnose_container(container)
        >>> print(f"Health Score: {report.health_score}/100")
        >>> if report.circular_dependencies:
        ...     print("Circular dependencies found!")
        >>> if report.warnings:
        ...     for warning in report.warnings:
        ...         print(f"⚠️  {warning}")
    """
    from .types import Lifetime

    registrations = container._registrations
    total = len(registrations)

    # 统计生命周期
    singleton_count = 0
    transient_count = 0
    scoped_count = 0

    for registration in registrations.values():
        # lifetime 是 Lifetime 枚举
        if registration.lifetime == Lifetime.SINGLETON:
            singleton_count += 1
        elif registration.lifetime == Lifetime.TRANSIENT:
            transient_count += 1
        elif registration.lifetime == Lifetime.SCOPED:
            scoped_count += 1

    # 检查循环依赖
    circular = _detect_circular_dependencies(container)

    # 检查无法解析的服务
    unresolvable = []
    warnings = []

    for key in registrations:
        try:
            container.resolve(key)
        except Exception as e:
            unresolvable.append(key)
            warnings.append(f"{_format_key(key)}: {e}")

    # 计算健康评分
    health_score = 100.0
    if circular:
        health_score -= len(circular) * 20
    if unresolvable:
        health_score -= len(unresolvable) * 10
    health_score = max(0, health_score)

    return ContainerDiagnostic(
        total_services=total,
        singleton_count=singleton_count,
        transient_count=transient_count,
        scoped_count=scoped_count,
        circular_dependencies=circular,
        unresolvable_services=unresolvable,
        warnings=warnings,
        health_score=health_score,
    )