跳到主要内容
版本:3.1

自定义组件注入

解决什么问题​

Aegis 框架通过 Component.deps.json 驱动组件的自动发现和注册。接入方不需要手动在 Startup.cs 中逐个调用 services.AddXxx(),只需要在配置文件中声明需要的组件名,框架启动时自动装配,装配顺序由框架按依赖与优先级排定。

Aegis.Component 提供了这个自动注册机制的基础抽象:组件注册器基类(ComponentRegister)、声明式 DI 注册特性(LifetimeAttribute)、组件注册结果(ComponentRegisterResult)。

如何引入​

NuGet 包:Aegis.Component

注册方式:由 Aegis.Core.Infrastructure 中的 AegisApplication 驱动,接入方不需要手动注册。只需在项目根目录放置 Component.deps.json 文件:

{
"Components": {
"Load": ["组件名1", "组件名2"]
}
}
  • Load:双阶段公共基底清单,服务阶段并入 Services、中间件阶段并入 Middlewares,对应 ComponentRegister.ComponentName
  • 清单是纯集合:列表顺序不影响任何行为,装配序由框架按 DependsOn > Order > 字典序排定,缺失依赖自动拉入(规则见Component.deps.json 组件清单)

配置:该包本身不需要 appsettings.json 配置。Component.deps.json 作为独立 JSON 文件通过 configuration.AddJsonFile() 加载。

使用示例​

使用 LifetimeAttribute 自动注册服务​

在类上标注 [Lifetime] 特性,框架启动时会自动将该类注册到 DI 容器:

using Aegis.Component.Lifetimes;
using Microsoft.Extensions.DependencyInjection;

// 定义接口
public interface ITestComponent
{
void Test();
}

// 用 Lifetime 标注实现类,指定生命周期和注册类型
[Lifetime(ServiceLifetime.Scoped, typeof(ITestComponent))]
public class TestComponent : ITestComponent
{
public void Test()
{
Console.WriteLine("测试获取");
}
}

控制器中直接注入使用:

public class TestController : ControllerBase
{
private readonly ITestComponent _testComponent;

public TestController(ITestComponent testComponent)
{
_testComponent = testComponent;
}
}

LifetimeAttribute 支持在同一个类上多次标注,用于将同一实现注册到多个服务类型:

[Lifetime(ServiceLifetime.Scoped, typeof(IEventHandler))]
[Lifetime(ServiceLifetime.Scoped, typeof(IInitializable))]
public class MyService : IEventHandler, IInitializable
{
// ...
}

自定义组件注册器​

当组件需要更复杂的注册逻辑(如读取配置、注册多个服务)时,继承 ComponentRegister:

using Aegis.Component;

public class MyFeatureRegister : ComponentRegister
{
public override string ComponentName => "MyFeature";

public override ComponentRegisterResult RegisterService(AegisBuilder builder)
{
builder.Services.AddScoped<IMyService, MyServiceImpl>();
return ComponentRegisterResult.Success();
}

public override ComponentRegisterResult RegisterMiddleware(IApplicationBuilder app)
{
// 如果组件需要注册中间件
return ComponentRegisterResult.Success();
}
}

然后在 Component.deps.json 的 Load 清单中添加 "MyFeature" 即可。

扩展点​

类型用途
ComponentRegister组件注册基类,子类实现 ComponentName、RegisterService()、RegisterMiddleware()
ComponentRegister.DependsOn声明必需依赖:框架自动拉入缺失依赖并保证其先装配;可选依赖不要声明
ComponentRegister.Order装配顺序软优先级,默认 10000(不覆写的组件排在最后),越小越前,两阶段共用;没有位置诉求就不要覆写
ComponentRegister.HasMiddleware纯服务组件声明 false,中间件阶段自动跳过
LifetimeAttribute声明式 DI 注册,支持指定 ServiceLifetime 和可选的 RegisterType
AegisBuilder注册上下文,封装 IServiceCollection 和 IConfiguration

边界与限制​

  • Aegis.Component 是框架内部基础包,通常不需要在业务项目中单独引用。Aegis.Core.Infrastructure 已传递依赖它。
  • Component.deps.json 位于项目根目录,构建时需要确保输出到 AppContext.BaseDirectory。
  • 装配顺序不在清单里控制:组件的先后由 DependsOn(必需依赖)与 Order(位置诉求)声明在组件代码里,清单书写顺序不参与。