public TestService(ILogger logger, OneTimeOptions options, MonitorOptions monitor) { _logger = logger; _options = options; _monitor = monitor; _logger.LogInformation($"In TestService constructor!!! {options}"); _logger.LogInformation($"In TestService constructor!!! {_monitor}"); }
public TestServiceInject(ILogger <TestServiceInject> logger, IOptions <OneTimeOptions> options, IOptions <MonitorOptions> monitor) { _logger = logger; _options = options.Value; _monitor = monitor.Value; _logger.LogInformation($"In TestServiceInject constructor!!! {options}"); _logger.LogInformation($"In TestServiceInject constructor!!! {_monitor}"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "aspnet_webapi", Version = "v1" }); }); // added for this test services.AddOptions <OneTimeOptions>() .Bind(Configuration.GetSection(OneTimeOptions.Config)) .ValidateDataAnnotations(); services.AddOptions <SnapshotOptions>() .Bind(Configuration.GetSection(SnapshotOptions.Config)) .ValidateDataAnnotations(); services.AddOptions <MonitorOptions>() .Bind(Configuration.GetSection(MonitorOptions.Config)) .ValidateDataAnnotations(); // https://stackoverflow.com/questions/52258443/how-to-get-ioptions-in-configureservices-method-or-pass-ioptions-into-extension/52268943 // Option 1 for getting IOption into singleton, can only use the class var oneTime = new OneTimeOptions(); Configuration.GetSection(OneTimeOptions.Config).Bind(oneTime); // Option 2, can use IOptionsMonitor<MonitorOptions> or MonitorOptions as parameter // if use .Value, it will validate here. // but this generates ASP0000 warning and is not recommended by MS // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#recommendations #pragma warning disable ASP0000 using var serviceProvider = services.BuildServiceProvider(); #pragma warning restore ASP0000 // need to validate here since calling .Value later var monitor = serviceProvider.GetRequiredService <IOptions <MonitorOptions> >(); if (!monitor.IsValid(_logger)) { throw new ArgumentException("One or more Options are invalid"); } services.AddSingleton <ITestService>( new TestService(_logger, oneTime, monitor.Value) // constructed now ); services.AddSingleton <ITestServiceInject, TestServiceInject>(); // constructed on first call so Configure can validate }