如何在 ASP.NET 核心中自动配置服务?
How to automatically Configure services in ASP.NET core?
我想更改我的 Startup class 以扫描系统以查找实现接口的所有 classes,然后自动注册它们。我使用 Scrutor 只是为了让生活更轻松。
通常情况下,这很容易用类似这样的代码实现:
services.Scan(scan => scan
.FromAssemblyOf<ISomething>()
.AddClasses()
.AsImplementedInterfaces()
.WithTransientLifetime());
我的问题是我无法使用选项模式执行此操作。
我的创业公司通常有这样的东西:
services.Configure<GatewaySettings>(
options => _config.GetSection(nameof(GatewaySettings)).Bind(options));
这允许我将 class 注入到这样的构造函数中:
public Something( IOptions<GatewaySettings> myOptions)
{
use(myOptions.Value);
}
有没有办法(使用 Scrutor 会很好,但我愿意接受其他建议)来注册我的所有选项-classes。通过命名约定或用空接口装饰它们,我可以在代码库中轻松识别它们。我的问题是我不知道如何使用扫描的 classes 调用“services.Configure()”。
我正在有效地寻找实现此目标的方法:
services.Configure(, myScannedType,
options => _config.GetSection(myScannedType.GetName()).Bind(options));
我想更改我的 Startup class 以扫描系统以查找实现接口的所有 classes,然后自动注册它们。我使用 Scrutor 只是为了让生活更轻松。
通常情况下,这很容易用类似这样的代码实现:
services.Scan(scan => scan
.FromAssemblyOf<ISomething>()
.AddClasses()
.AsImplementedInterfaces()
.WithTransientLifetime());
我的问题是我无法使用选项模式执行此操作。
我的创业公司通常有这样的东西:
services.Configure<GatewaySettings>(
options => _config.GetSection(nameof(GatewaySettings)).Bind(options));
这允许我将 class 注入到这样的构造函数中:
public Something( IOptions<GatewaySettings> myOptions)
{
use(myOptions.Value);
}
有没有办法(使用 Scrutor 会很好,但我愿意接受其他建议)来注册我的所有选项-classes。通过命名约定或用空接口装饰它们,我可以在代码库中轻松识别它们。我的问题是我不知道如何使用扫描的 classes 调用“services.Configure()”。
我正在有效地寻找实现此目标的方法:
services.Configure(, myScannedType,
options => _config.GetSection(myScannedType.GetName()).Bind(options));