Why is not injected last version of configuration (appsettings.json)?

馋奶兔 提交于 2020-01-16 08:43:24

问题


I am trying to edit appsettings.json in runtime. I found great solution how to update this file:

https://stackoverflow.com/a/45986656/9684060

I did everything according to answer above:

1) Added MySettings to DI container (MySettings are added via AddTransient) services.ConfigureWritable(Configuration.GetSection(nameof(MySettings)));

2) Constructor injection

    private readonly IWritableOptions<MySettings> _cfg;

    public MyController(IWritableOptions<MySettings> cfg)
    {
        _cfg = cfg;
    }

Then I use it in my Create controller action.

public ActionResult Create(string value)
    {

           //Some specific code...

            MyCustomObj myObj = new MyCustomObj(value);

            //Update appsettings
            _cfg.Update(opt =>
            {
                opt.MyCollection.Add(myObj);
            });

            //Some specific code...

            return RedirectToAction(nameof(Overview));

    }

Configuration file is updated (updated MySettings object is serialized to file), but after redirection to Overview I have same collection without newly created object (Configuration without updated collection is injected into controller's constructor). I have to refresh page again and then I see updated configuration (Updated MySettings is injected).

I had suspect that it could be fault of IOptionsSnapshot interface, because it is scoped service. But scoped service should be alive only for the live time of the request and redirection is new request or am I wrong?

Same situation is when I try to delete some object from my collection. Page with all items (included deleted one) is rendered. Everything is ok when I refresh page.

来源:https://stackoverflow.com/questions/59677486/why-is-not-injected-last-version-of-configuration-appsettings-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!