跳到主要内容
版本:3.0.0

自定义组件注入

解决什么问题

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": {
"Services": ["组件名1", "组件名2"],
"Middlewares": ["组件名1"]
}
}
  • Services:按顺序注册的服务组件名称列表,对应 ComponentRegister.ComponentName
  • Middlewares:按顺序注册的中间件组件名称列表
  • 列表顺序即为注册顺序,框架会根据 DependsOn 校验依赖顺序是否正确

配置:该包本身不需要 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 的 Services 或 Middlewares 中添加 "MyFeature" 即可。

扩展点

类型用途
ComponentRegister组件注册基类,子类实现 ComponentNameRegisterService()RegisterMiddleware()
LifetimeAttribute声明式 DI 注册,支持指定 ServiceLifetime 和可选的 RegisterType
AegisBuilder注册上下文,封装 IServiceCollectionIConfiguration

边界与限制

  • Aegis.Component 是框架内部基础包,通常不需要在业务项目中单独引用。Aegis.Core.Infrastructure 已传递依赖它。
  • Component.deps.json 位于项目根目录,构建时需要确保输出到 AppContext.BaseDirectory
  • 组件注册顺序由 Component.deps.json 中的列表顺序决定,有依赖关系的组件需要先声明被依赖方。