VContainer-scoping/generate-child-with-code-first | 作用域——通过代码优先生成子作用域
也可以通过 C# 代码直接创建子作用域。
class LevelLoader
{
readonly LifetimeScope currentScope;
LifetimeScope instantScope;
public LevelLoader(LifetimeScope lifetimeScope)
{
currentScope = lifetimeScope;
}
public void Load()
{
// ... 通过任意异步方式加载资源
//
// await Addressables.LoadAssetAsync...
//
// 为包含此 LevelLoader 实例的容器创建一个c子作用域。
instantScope = currentScope.CreateChild();
// 基于 LifetimeScope 预制体创建子作用域
instantScope = currentScope.CreateChildFromPrefab(
lifetimeScopePrefab);
// 基于 LifetimeScope 预制体创建并添加额外注册
instantScope = currentScope.CreateChildFromPrefab(
lifetimeScopePrefab, builder =>
{
builder.RegisterInstance(someExtraAsset);
builder.RegisterEntryPoint<ExtraEntryPoint>();
// ...
});
// 创建带额外注册的子作用域
instantScope = currentScope.CreateChild(builder =>
{
// ...
});
// 通过 `IInstaller` 创建子作用域并添加额外注册
instantScope = currentScope.CreateChild(extraInstaller);
// 额外注册的入口点会在作用域创建后立即运行...
// 或者直接使用作用域实例。
var foo = instantScope.Container.Resolve<Foo>();
}
public void Unload()
{
// 注意,作用域隐式创建了 `LifetimeScope`。
// 使用 `Dispose` 来安全销毁作用域。
instantScope.Dispose();
// ... 卸载相关资源
}
}

浙公网安备 33010602011771号