Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to access strongly-typed settings while still in ConfigureServices()?

I have code similar to this in Startup.cs

services.Configure<AppSettings>(
    Configuration.GetSection("AppSettings"));

services.AddScoped<IMyService, MyService>();
services.AddScoped((_) => MyFactory.Create(
    Configuration["AppSettings:Setting1"],
    Configuration["AppSettings:Setting2"],
    Configuration["AppSettings:Setting3"]));

I'd like to pass an instance of AppSettings into MyFactory.Create(). Is such an instance available yet? Is there a way to get an instance of it?

I'd like to eliminate the redundancy in my current code, and take advantage of some of the benefits of my AppSettings class (for example, it has some defaults and some handy read-only properties that are functions of other properties).

It might look something like this:

services.Configure<AppSettings>(
    Configuration.GetSection("AppSettings"));

var appSettings = ???;
services.AddScoped<IMyService, MyService>();
services.AddScoped((_) => MyFactory.Create(appSettings));

What goes in place of the "???"?

like image 531
Chris Avatar asked Apr 04 '17 15:04

Chris


1 Answers

You can use the Microsoft.Extensions.Configuration.Binder package for this. This provides a Bind extension method on the IConfigurationSection interface and allows you to pass in an instance of your options class. It will attempt to bind the configuration values to your class properties recursively.

Quoting the documentation:

Attempts to bind the given object instance to configuration values by matching property names against configuration keys recursively.

In your case the code would look like the following:

// Create a new, empty instance of AppSettings
var appSettings = new AppSettings(); 

// Bind values from the 'AppSettings' section to the instance
Configuration.GetSection("AppSettings").Bind(appSettings);

Please keep in mind that if you still want to inject IOptions<AppSettings> in your application via dependency injection, you'll still have to configure the options via

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
like image 113
Henk Mollema Avatar answered Nov 10 '22 13:11

Henk Mollema