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.
IWriteableOptions<T>
as Transient. So this shouldn't be problem or Am I wrong?services.AddTransient<IWritableOptions<T>
– Outherod