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();

        // ... 卸载相关资源
    }
}
posted @   凌雪寒  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示