本日は VContainer の小ネタ枠です。
Project root LifetimeScopeを設定する手順について記事に残します。
前回記事
以下の前回記事のプロジェクトを利用します。
bluebirdofoz.hatenablog.com
Project root LifetimeScopeを設定する
Project root LifetimeScope は全ての LifetimeScope の親になる LifetimeScope です。
vcontainer.hadashikick.jp
Project root LifetimeScope と子の LifetimeScope を作成する
親となる Project root LifetimeScope とその子になる LifetimeScope を作成します。
以下の2つの LifetimeScope を用意しました。
・RootParentLifetimeScope.cs
using VContainer; using VContainer.Unity; namespace ProjectRootSample { public class RootParentLifetimeScope : LifetimeScope { protected override void Configure(IContainerBuilder builder) { // HelloWorldServiceをDIコンテナに登録する builder.Register<HelloWorldService>(Lifetime.Singleton); } } }
・GameLifetimeScope.cs
using UnityEngine; using VContainer; using VContainer.Unity; namespace ProjectRootSample { public class GameLifetimeScope : LifetimeScope { [SerializeField] private HelloScreen helloScreen; protected override void Configure(IContainerBuilder builder) { // GamePresenterをVContainerのEntryPointに登録する builder.RegisterEntryPoint<GamePresenter>(); // HelloScreenコンポーネントをDIコンテナに登録する builder.RegisterComponent<HelloScreen>(helloScreen); } } }
GameLifetimeScope.cs は HelloWorldService を参照する必要があるので、RootParentLifetimeScope.cs の子 LifetimeScope である必要があります。
Project root LifetimeScope を設定するため、この LifetimeScope をアタッチしたプレハブを作成します。
Assets で右クリックから[Create -> VContainer -> VContainerSettings]を実行して適当なフォルダに VContainerSettings を作成します。
作成した VContainerSettings の[RootLifetimeScope]に先ほどのプレハブを登録します。
VContainerSettings は作成と同時にプロジェクトの[PreloadAssets]に登録されており、本設定はプロジェクト全体で有効です。
動作確認
シーン内に GameLifetimeScope.cs のみアタッチしたシーンを再生して動作を確認します。
自動的に親 LifetimeScope として RootParentLifetimeScope.cs が動作するため、参照が解決して正常に動作します。
試しに VContainerSettings のプレハブ設定を削除して再び再生してみます。
以下の通り、HelloWorldService の参照を解決できずエラーが発生しました。
Project root LifetimeScope はプロジェクトにプリロードされるため、シーンを跨いで参照することも可能です。