### **코드를 통한 자식 스코프 생성** `LifetimeScope`는 코드를 통해 부모 `LifetimeScope`의 자식으로 생성될 수 있습니다. 이는 씬 로딩 없이, 순수 C# 코드로 DI 컨테이너 계층을 구성할 때 사용됩니다. - **기본 자식 스코프 생성:** `currentScope.CreateChild()` 메서드를 사용하여 현재 `LifetimeScope`의 자식 스코프를 생성합니다. C# ``` class LevelLoader { readonly LifetimeScope currentScope; LifetimeScope instantScope; // 생성된 자식 스코프를 저장할 변수 public LevelLoader(LifetimeScope lifetimeScope) { currentScope = lifetimeScope; // 현재 LifetimeScope를 주입받음 } public void Load() { // 비동기 에셋 로딩 등 (예: await Addressables.LoadAssetAsync...) // 현재 LifetimeScope의 자식으로 새로운 스코프 생성 instantScope = currentScope.CreateChild(); // ... } public void Unload() { // 스코프 파괴 instantScope.Dispose(); // ... 에셋 언로드 } } ``` - `CreateChild()`는 새로운 `GameObject`를 생성하고, 그 `GameObject`에 `LifetimeScope` 컴포넌트를 추가하여 반환합니다. 이 새로 생성된 `LifetimeScope`는 `currentScope`의 자식이 됩니다. - `Dispose()` 메서드를 호출하여 자식 스코프를 안전하게 파괴하고 관련 리소스를 해제해야 합니다. - **프리팹(Prefab)을 사용하여 자식 스코프 생성:** `LifetimeScope` 프리팹을 미리 만들어두었다면, 이를 기반으로 자식 스코프를 생성할 수 있습니다. C# ``` // LifetimeScope 프리팹으로 생성 instantScope = currentScope.CreateChildFromPrefab(lifetimeScopePrefab); ``` - `lifetimeScopePrefab`은 `LifetimeScope` 컴포넌트를 가진 프리팹 인스턴스여야 합니다. - **추가적인 등록을 포함하여 자식 스코프 생성:** 자식 스코프를 생성할 때, 해당 스코프에만 적용될 추가적인 의존성 등록을 정의할 수 있습니다. 이는 람다 표현식 또는 `IInstaller` 인터페이스를 통해 가능합니다. C# ``` // LifetimeScope 프리팹과 추가 등록을 포함하여 생성 instantScope = currentScope.CreateChildFromPrefab( lifetimeScopePrefab, builder => { builder.RegisterInstance(someExtraAsset); // 특정 에셋 인스턴스 등록 builder.RegisterEntryPoint<ExtraEntryPoint>(); // 추가 진입점 등록 }); // 프리팹 없이 추가 등록을 포함하여 생성 instantScope = currentScope.CreateChild(builder => { // ... 추가 등록 }); // IInstaller를 사용하여 추가 등록 instantScope = currentScope.CreateChild(extraInstaller); // extraInstaller는 IInstaller 구현체 ``` - `builder` 람다 또는 `IInstaller`를 통해 정의된 의존성들은 새로 생성된 자식 스코프의 컨테이너에만 등록됩니다. - 이렇게 추가적으로 등록된 `EntryPoint`는 스코프가 생성되는 즉시 실행됩니다. - **스코프 내 객체 직접 해결(Resolve):** 생성된 자식 스코프의 컨테이너를 직접 참조하여 객체를 해결할 수도 있습니다. C# ``` // 또는 스코프된 인스턴스를 직접 사용할 수 있습니다. var foo = instantScope.Container.Resolve<Foo>(); ``` - 이 방법은 스코프가 생성된 후 바로 특정 의존성을 가져와야 할 때 유용합니다. ### 요약 VContainer에서 `LifetimeScope.CreateChild()` 및 `CreateChildFromPrefab()` 메서드를 통해 코드로 자식 스코프를 생성하는 방법을 상세히 설명합니다. 이 기능은 게임의 특정 레벨, UI 패널, 또는 동적으로 생성되는 오브젝트 그룹 등 자체적인 의존성 스코프를 가져야 하는 시나리오에서 강력한 유연성을 제공합니다. 또한, 자식 스코프 생성 시 추가적인 등록을 정의하고, 생성된 스코프를 안전하게 폐기하는 방법을 명확히 제시하여 효율적인 리소스 관리를 돕습니다. --- 이전 : [[6.2 Generate child scope via scene or prefab]] | 다음 : [[6.4 Project root LifetimeScope]]