简体   繁体   English

稍后在执行某些任务时如何更新asp.net core di容器

[英]How to update asp.net core di container later on when some task is performed

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. 我将设置值保留在di容器上,可以通过管理页面更改设置,但是当我再次在服务集合中添加新的设置值时,它会给我旧的设置值。 How to update di container values/service on .net core. 如何在.net核心上更新容器的值/服务。

Instead of injecting your strong-typed settings directly, you need to inject IOptionsSnapshot<T> , where T is your settings class. 无需直接注入强类型设置,而是需要注入IOptionsSnapshot<T> ,其中T是您的设置类。 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: 您也可以将依赖项注入设置为直接使用IOptionsSnapshot

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. 然后,您可以像以前一样继续将MySettings注入到控制器中。

Note: IOptionsSnapshot is available in ASP.NET Core 1.1+. 注意: IOptionsSnapshot在ASP.NET Core 1.1+中可用。 There is no way to reload settings in any previous version. 无法在任何先前版本中重新加载设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM