Skip to content
English

应用装配与生命周期 ​

仅使用 Core 的控制台应用 ​

创建 .NET 控制台工程,直接依赖只安装 GeWuYou.GFramework.Core。NuGet 会解析该包的传递依赖。把 Core 启停示例 复制到新项目,再将 Program.cs 替换为下面这一行,执行 dotnet run。

bash
dotnet new console -n CoreLifecycle
cd CoreLifecycle
dotnet add package GeWuYou.GFramework.Core --version 1.1.0
csharp
await MinimalApp.CoreOnlyLifecycle.RunAsync().ConfigureAwait(false);
csharp
// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0

using System;
using System.Threading.Tasks;
using GFramework.Core.Abstractions.Lifecycle;
using GFramework.Core.Architectures;
using Microsoft.Extensions.DependencyInjection;

namespace MinimalApp;

/// <summary>Runs the lifecycle using only the Core package and its dependencies.</summary>
internal static class CoreOnlyLifecycle
{
    /// <summary>Starts the architecture, runs one operation and joins business stop and disposal.</summary>
    internal static async Task RunAsync()
    {
        var app = new ConsoleArchitecture();
        await app.InitializeAsync().ConfigureAwait(false);
        try
        {
            Console.WriteLine("Application work");
        }
        finally
        {
            await app.DestroyAsync().ConfigureAwait(false);
        }
    }

    /// <summary>Composition root for the console host.</summary>
    private sealed class ConsoleArchitecture : Architecture
    {
        /// <inheritdoc />
        protected override void ConfigureServices(IServiceCollection services)
        {
            services.AddComponent<Worker>();
        }
    }

    /// <summary>Receives startup and shutdown callbacks from Architecture.</summary>
    private sealed class Worker : IInitializable, IDestroyable, IDisposable
    {
        /// <inheritdoc />
        public void Initialize() => Console.WriteLine("Started");

        /// <inheritdoc />
        public void Destroy() => Console.WriteLine("Stopped");

        /// <inheritdoc />
        public void Dispose() => Console.WriteLine("Disposed");
    }
}

输出依次为 Started、Application work、Stopped 和 Disposed。IDestroyable 回调负责停止业务,随后由 DI 容器释放它创建的实例。长时间运行的宿主关闭时,先停止接纳新操作,等待在途操作结束,再调用并等待 DestroyAsync。

注册和启动 ​

在 ConfigureServices 登记依赖。普通类使用标准 DI 注册;需要初始化、停止或两者兼有的服务使用 AddComponent。通过构造函数传入依赖,保留每个组件的一个注册服务键。

cs
// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0

using GFramework.Core.Architectures;
using Microsoft.Extensions.DependencyInjection;

namespace MinimalApp;

/// <summary>
///     示例架构:只使用标准 DI 注册普通服务,不引入 Model/System/Utility 角色。
///     Architecture 在这里只提供实例级的初始化/停止编排与日志工厂所有权。
/// </summary>
internal sealed class OrderArchitecture : Architecture
{
    /// <summary>描述服务注册;此阶段只记录描述,不解析实例。</summary>
    /// <param name="services">当前架构将构建和拥有的服务集合。</param>
    protected override void ConfigureServices(IServiceCollection services)
    {
        // 普通服务:无角色标记、无 ContextAware、无基类要求。
        services.AddSingleton<OrderService>();
        services.AddSingleton<OrderProcessor>();
    }

    /// <summary>宿主准备完成后通过标准解析使用普通服务。</summary>
    protected override void OnStarted()
    {
        var processor = Services.GetRequiredService<OrderProcessor>();
        processor.Process("boot");
    }

    /// <summary>提交一条示例订单并输出处理日志。</summary>
    /// <param name="orderId">订单编号。</param>
    public void PlaceDemoOrder(string orderId)
    {
        var processor = Services.GetRequiredService<OrderProcessor>();
        processor.Process(orderId);
    }
}

生命周期 ​

  1. 等待 InitializeAsync 创建 provider、按顺序启动组件并完成宿主接线。
  2. 宿主就绪后解析服务并开放用户操作。对 scoped 服务在操作范围内创建 scope。
  3. 退出时等待 DestroyAsync。组件逆序停止,宿主分离后释放 provider。

order 从小到大排列启动回调,同值按登记顺序。把依赖其他组件就绪的工作放进生命周期回调。

所有权 ​

DI 创建的可释放服务随 provider 或 scope 释放。通过实例重载登记已创建的组件时,由原调用者负责释放实例,Architecture 执行已登记的业务停止。

相关主题:异步初始化 · 依赖注入。

Apache 2.0 许可证