### **씬 또는 프리팹을 통한 자식 스코프 생성** **1. 애드티브 씬(Additive Scene)을 자식으로 만드는 방법** 새로운 씬을 애드티브 방식으로 로드할 때, 로드되는 씬의 `LifetimeScope`가 기존 부모 `LifetimeScope`의 자식이 되도록 설정할 수 있습니다. - **씬 로드 시 부모 설정:** `LifetimeScope.EnqueueParent(parent)` 유틸리티를 `using` 문과 함께 사용합니다. 이 `using` 블록 내에서 로드되는 모든 `LifetimeScope`는 지정된 `parent` 스코프의 자식이 됩니다. C# ``` class SceneLoader { readonly LifetimeScope parent; public SceneLoader(LifetimeScope lifetimeScope) { parent = lifetimeScope; // 현재 LifetimeScope를 주입받아 부모로 사용 } IEnumerator LoadSceneAsync() { using (LifetimeScope.EnqueueParent(parent)) // 이 블록 내에서 로드되는 스코프는 'parent'의 자식이 됨 { var loading = SceneManager.LoadSceneAsync("...", LoadSceneMode.Additive); while (!loading.isDone) { yield return null; } } } } ``` - **UniTask 예시:** 비동기 작업에 UniTask를 사용하는 경우에도 동일하게 적용됩니다. async UniTask LoadSceneAsync() { using (LifetimeScope.EnqueueParent(parent)) { await SceneManager.LoadSceneAsync("...", LoadSceneMode.Additive); } } ``` - **씬에서 부모 찾기:** `LifetimeScope`는 `GameObject`이므로, `LifetimeScope.Find<BaseLifetimeScope>()`와 같이 씬에서 특정 타입의 `LifetimeScope`를 찾아 부모로 지정할 수도 있습니다. **2. 다음 씬에 추가적인 등록(Register)을 추가하는 방법** 비동기 에셋 로딩 후 컨텍스트를 최종화해야 하는 경우처럼, 아직 로드되지 않은 다음 씬에 추가적인 의존성을 등록하고 싶을 때 유용합니다. - **`LifetimeScope.Enqueue()` 사용:** `using (LifetimeScope.Enqueue(builder => { /* 추가 등록 */ }))` 블록을 사용합니다. 이 블록 내에서 생성되는 모든 `LifetimeScope`에 지정된 `builder` 람다 표현식이 추가적으로 적용됩니다. C# ``` // 이 블록 내에서 생성되는 LifetimeScope는 추가적으로 등록됩니다. using (LifetimeScope.Enqueue(builder => { // 아직 로드되지 않은 다음 씬을 위한 등록 builder.RegisterInstance(extraInstance); })) { // 씬 로딩... } ``` - **`IInstaller` 타입으로 등록:** `IInstaller` 인터페이스를 구현하는 클래스를 통해 여러 등록을 한 번에 정의하고 `Enqueue`에 전달할 수도 있습니다. 코드 스니펫 ``` class FooInstaller : IInstaller { public void Install(IContainerBuilder builder) { builder.Register<ExtraType>(Lifetime.Scoped); } } using (LifetimeScope.Enqueue(new FooInstaller())) // IInstaller 인스턴스를 직접 전달 { // 씬 로딩... } ``` - **`EnqueueParent()`와 `Enqueue()` 동시 사용:** 두 기능을 조합하여 부모를 지정하면서 동시에 추가적인 등록을 수행할 수 있습니다. C# ``` using (LifetimeScope.EnqueueParent(parent)) using (LifetimeScope.Enqueue(builder => { /* ... */ })) { // 씬 로딩... } ``` **3. 인스펙터에서 부모를 미리 설정하는 방법** `LifetimeScope` 컴포넌트의 인스펙터에서 `Parent` 필드에 다른 `LifetimeScope`를 참조하여 부모-자식 관계를 직접 설정할 수 있습니다. - **`LifetimeScope` 컴포넌트의 `Parent` 필드:** Unity 에디터에서 `LifetimeScope`가 있는 `GameObject`를 선택하고, 인스펙터의 `Parent` 필드에 부모가 될 `LifetimeScope` 인스턴스를 할당합니다. - **주의사항 (CAUTION):** 씬이 "isLoaded" 상태가 될 때, 인스펙터에 설정된 `Parent` 타입의 `LifetimeScope`를 찾지 못하면 에러가 발생합니다. 이는 계층 구조가 올바르게 설정되어야 함을 의미합니다. ### 요약 VContainer에서 `LifetimeScope`의 유연한 부모-자식 관계 설정 방법을 다룹니다. 특히 씬 로딩(애드티브 씬) 과정에서 `EnqueueParent` 및 `Enqueue` 유틸리티를 사용하여 동적으로 스코프의 계층 구조와 등록을 제어하는 방법을 강조합니다. 또한, Unity 에디터의 인스펙터를 통해 정적으로 부모를 설정하는 방법도 제공하여, 다양한 게임 개발 시나리오에 맞춰 DI 스코프를 효과적으로 관리할 수 있도록 지원합니다. --- 이전 : [[6.1 Lifetime Overview]] | 다음 : [[6.3 Generate child scope with code first]]