我正在使用 .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; });
我过去也有类似的需求,这就是我所做的:
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>();
或者,您可以使用 ServiceProviderServiceExtensions
GetService<>
或 GetRequiredService<>
按类型获取您需要的服务。另外,请谨慎使用 BuildServiceProvider,它可能会创建重复的服务,如此处所述。
希望这有帮助。