1

I've kept settings values on di-container and settings can be changed through the management page but when i again add new settings value in service collection it's giving me old settings values. How to update di container values/service on .net core.

1 Answers1

2

Instead of injecting your strong-typed settings directly, you need to inject IOptionsSnapshot<T>, where T is your settings class. This will cause it update the values when the configuration is reloaded. For example:

public class MyController : Controller
{
    private readonly IOptionsSnapshot<MySettings> _settings;

    public MyController(IOptionsSnapshot<MySettings> settings)
    {
        _settings = settings;
    }

    ...
}

You can alternatively set up the dependency injection to use IOptionsSnapshot directly:

services.Configure<MySettings>(Configuration.GetSection("MySettings"));
services.AddScoped(cfg => cfg.GetService<IOptionsSnapshot<MySettings>>().Value);

Then, you can continue to just inject MySettings into your controllers as before.

Note: IOptionsSnapshot is available in ASP.NET Core 1.1+. There is no way to reload settings in any previous version.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444