IOption<> 的实现及在Swagger 中的应用
2022-07-14 15:09 qgbo 阅读(109) 评论(0) 收藏 举报
1. addoption();
这个方法,增加了以下的注入:
这个方法,增加了以下的注入:
public static IServiceCollection AddOptions(this IServiceCollection services) { ThrowHelper.ThrowIfNull(services); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(UnnamedOptionsManager<>))); services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>))); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>))); services.TryAdd(ServiceDescriptor.Transient(typeof(IOptionsFactory<>), typeof(OptionsFactory<>))); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitorCache<>), typeof(OptionsCache<>))); return services; }
UnnamedOptionsManager 中,injected in OptionsFactory,后者又有IConfigOption<> 的注入
So, 当我们应用中的构造 传入 IOption<> 的时候,实际传入的类型是UnnamedOptionsManager<>, 进而包含了OptionsFactory,又有 IConfigOption<>。
而IConfigOption<>, 是我们应用启动时注入的,这个中间过程,框架封装了。 UnnamedOptionsManager 这是 internal。 这个IOption<> 是单例的。
当我们应用中的构造 传入 IOptionsMonitor<> 的时候,实际传入的类型是OptionsMonitor<>, 进而包含了IOptionsChangeTokenSource 这在 source 变化的时候,会触发改变。
应用:
当webapi 展示swagger 的时候,这个界面固定了,我们设置的 openapi 也不会变化。
1 public static IServiceCollection AddSwaggerGen( 2 this IServiceCollection services, 3 Action<SwaggerGenOptions> setupAction = null) 4 { 5 // Add Mvc convention to ensure ApiExplorer is enabled for all actions 6 services.Configure<MvcOptions>(c => 7 c.Conventions.Add(new SwaggerApplicationConvention())); 8 9 // Register custom configurators that takes values from SwaggerGenOptions (i.e. high level config) 10 // and applies them to SwaggerGeneratorOptions and SchemaGeneratorOptoins (i.e. lower-level config) 11 services.AddTransient<IConfigureOptions<SwaggerGeneratorOptions>, ConfigureSwaggerGeneratorOptions>(); 12 services.AddTransient<IConfigureOptions<SchemaGeneratorOptions>, ConfigureSchemaGeneratorOptions>(); 13 14 // Register generator and it's dependencies 15 services.TryAddTransient<ISwaggerProvider, SwaggerGenerator>(); 16 services.TryAddTransient(s => s.GetRequiredService<IOptions<SwaggerGeneratorOptions>>().Value); 17 services.TryAddTransient<ISchemaGenerator, SchemaGenerator>(); 18 services.TryAddTransient(s => s.GetRequiredService<IOptions<SchemaGeneratorOptions>>().Value);
第15行,是swagger 的应用入口点。这个里面包含了返回OpenapiDocument 的方法,引入了 SwaggerGeneratorOptions
而后者在16 行定义。
这个定义能起效,是在11 行定义,他的返回值是 ConfigureSwaggerGeneratorOptions
如果应用需要swgger 界面动态变化,需要覆盖 第16 行
气功波(18037675651)