.NET 如何在启动期间访问 TOptions(选项模式)

Mof*_*fen 5 .net c# .net-core asp.net-core .net-6.0

我正在使用.NET 选项模式来管理我的配置。

控制器中需要此配置(通过依赖注入很容易),但也需要在应用程序启动期间配置其他服务。

我本以为通用Services.Configure<MyOptionsClass>方法会返回 MyOptionsClass 的实例,但不幸的是它返回 IServiceCollection?

有没有一种干净的方法可以在启动期间访问 MyOptionsClass 的绑定实例?

var builder = WebApplication.CreateBuilder(args);

// Setup MyOptionsClass for DI
var unwantedServiceCollection = builder.Services.Configure<MyOptionsClass>(builder.Configuration.GetSection(MyOptionsClass.ConfigName));

// Already need to be able to access MyOptionsClass here:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => { options.Authority = instanceOfMyOptionsClass.Authority; });
Run Code Online (Sandbox Code Playgroud)

Par*_*kar 7

我过去也有类似的需求,这就是我所做的:

var configOptions = builder.Configuration.GetSection(MyOptionsClass.ConfigName);

//You can also add data annotations to your config validate it on start
builder.Services
            .AddOptions<MyOptionsClass>()
            .Bind(configOptions)
            .ValidateDataAnnotations()
            .ValidateOnStart();

var configInstance = configOptions.Get<MyOptionsClass>();
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用ServiceProviderServiceExtensions GetService<>GetRequiredService<>按其类型获取所需的服务。另外,请谨慎使用 BuildServiceProvider,它可能会创建重复的服务,如此处所述

希望这可以帮助。


归档时间:

查看次数:

2222 次

最近记录:

3 年,2 月 前