0

I know use this can do

services.AddOptions<MyConfigModel>()
        .Bind(Configuration.GetSection(nameof(MyConfigModel)))
        .ValidateDataAnnotations();

But I don't like access by option.Value.xxx.

I prefer:

var myconfig = new MyConfigModel();
Configuration.Bind(nameof(MyConfigModel), myconfig);   

services.AddSingleton(myconfig);
huang
  • 919
  • 11
  • 22
  • 1
    You could just use [`TryValidateObject`](https://stackoverflow.com/a/17138972/2630078) directly, but realise that the options pattern provides a number of benefits (e.g. auto-reload). – Kirk Larkin Jul 19 '19 at 10:51
  • Does it watch the file changes ? – huang Jul 19 '19 at 11:04
  • See the [docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2#reload-configuration-data-with-ioptionssnapshot). – Kirk Larkin Jul 19 '19 at 11:05
  • @KirkLarkin Does "Options Validation" validate recursively entire object graph ? Such as Class nested Class. – huang Jul 19 '19 at 11:57
  • I don't *think* it does, but I *think* that's because `TryValidateObject` doesn't do it out of the box either. Honestly, I haven't tried it so I don't know for sure. – Kirk Larkin Jul 19 '19 at 12:25

1 Answers1

2

For avoiding resolve MyConfigModel by IOptions<MyConfigModel>.Value, you could try register MyConfigModel like

services.AddOptions<MyConfigModel>()
    .Bind(Configuration.GetSection(nameof(MyConfigModel)))
    .ValidateDataAnnotations();
services.AddScoped(serviceProvider => serviceProvider.GetRequiredService<IOptions<MyConfigModel>>().Value);

And then use like

public class HomeController : Controller
{       
    private readonly MyConfigModel _myConfigModel2;
    public HomeController(MyConfigModel myConfigModel)
    {
        _myConfigModel2 = myConfigModel;
    }              
}
Edward
  • 28,296
  • 11
  • 76
  • 121