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

0

0

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

https://mcmap.net/q/321986/-how-to-update-values-into-appsetting-json

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.

Outherod answered 10/1, 2020 at 7:57 Comment(4)
See this stackoverflow postBooher
I am registering IWriteableOptions<T> as Transient. So this shouldn't be problem or Am I wrong? services.AddTransient<IWritableOptions<T>Outherod
U ever found a solution to this? I have the same problem :)Moniz
Unfortunately no :(Outherod

© 2022 - 2024 — McMap. All rights reserved.