https://github.com/khellang/Scrutor
- 可扫描
- 实现了一个装饰器
扫描
var collection = new ServiceCollection();
collection.Scan(scan => scan
// 从 ITransientService 接口所在的程序集开始扫描
.FromAssemblyOf<ITransientService>()
// 添加所有实现了 ITransientService 接口的类
.AddClasses(classes => classes.AssignableTo<ITransientService>())
// 注册为它们实现的所有接口(例如 IA, IB 等)
.AsImplementedInterfaces()
// 设置生命周期为 Transient(每次请求都创建新实例)
.WithTransientLifetime()
// 继续添加实现了 IScopedService 接口的类
.AddClasses(classes => classes.AssignableTo<IScopedService>())
// 只注册为 IScopedService 接口(而不是所有实现接口)
.As<IScopedService>()
// 设置生命周期为 Scoped(每个作用域共享一个实例)
.WithScopedLifetime()
// 添加实现了开放泛型接口 IOpenGeneric<> 的类
.AddClasses(classes => classes.AssignableTo(typeof(IOpenGeneric<>)))
// 注册为它们实现的具体泛型接口(如 IOpenGeneric<string>)
.AsImplementedInterfaces()
// 默认生命周期为 Transient(如果不指定的话)
// 添加实现了带两个泛型参数的接口 IQueryHandler<TQuery, TResult> 的类
.AddClasses(classes => classes.AssignableTo(typeof(IQueryHandler<,>)))
// 同样注册为具体实现的接口(如 IQueryHandler<GetUserQuery, User>)
.AsImplementedInterfaces()
);
// 如果你想查看注册的服务或构建 ServiceProvider,可以继续:
var serviceProvider = collection.BuildServiceProvider();
装饰器
var collection = new ServiceCollection();
// 首先,将我们的服务添加到集合中。
collection.AddSingleton<IDecoratedService, Decorated>();
// 然后,使用 Decorator 类型装饰 Decorated 服务。
collection.Decorate<IDecoratedService, Decorator>();
// 最后,使用 OtherDecorator 类型装饰 Decorator。
// 如你所见,OtherDecorator 需要一个独立的服务 IService。
// 我们可以通过 provider 参数获取该服务。
collection.Decorate<IDecoratedService>(
(inner, provider) => new OtherDecorator(inner, provider.GetRequiredService<IService>())
);
var serviceProvider = collection.BuildServiceProvider();
// 当我们解析 IDecoratedService 服务时,会得到以下结构:
// OtherDecorator -> Decorator -> Decorated
var instance = serviceProvider.GetRequiredService<IDecoratedService>();