亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET?Core選項(xiàng)接口介紹

 更新時(shí)間:2022年02月23日 09:00:54   作者:癡者工良  
這篇文章介紹了ASP.NET?Core中的選項(xiàng)接口,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

首先要了解 ASP.NET Core 中的配置,請(qǐng)點(diǎn)擊這里了解:http://chabaoo.cn/article/238451.htm

1,選項(xiàng)接口

ASP.NET Core 中的選項(xiàng)接口,一共有三個(gè),分別是:

  • IOptions<TOptions>
  • IOptionsSnapshot<TOptions>
  • IOptionsMonitor<TOptions>

這三種方式都可以獲取到配置,區(qū)別在于生命周期和文件監(jiān)控等。

2,注入配置與IOptions

首先我們創(chuàng)建一個(gè) ASP.NET Core API 項(xiàng)目,添加一個(gè) test.json 文件,內(nèi)容如下:

{
  "Title": "測(cè)試",
  "Name": "測(cè)試測(cè)試"
}

再創(chuàng)建一個(gè)與之對(duì)應(yīng)的模型類(lèi):

    public class TestModel
    {
        public string Title { get; set; }
        public string Name { get; set; }
    }

然后在 Startup 的 ConfigureServices 方法中加上:

            services.Configure<TestModel>(new ConfigurationBuilder().AddJsonFile("test.json").Build());

這樣就可以自動(dòng)注入配置服務(wù)了。那么我們?nèi)绾谓邮者@個(gè)配置呢?
我們可以先使用 IOptions<T> 來(lái)接收。

添加一個(gè)控制器,名字隨意,其內(nèi)容如下:

    public class TestController : ControllerBase
    {
        private readonly TestModel _options;
        public TestController(IOptions<TestModel> options)
        {
            _options = options.Value;
        }
    }

這樣就可以接收接入的配置了。

這就是 IOptions<TOptions> 的使用。

IOptions<TOptions> 有以下特征:

不支持:

  • 在應(yīng)用啟動(dòng)后讀取配置數(shù)據(jù)。
  • 命名選項(xiàng)

可以:

  • 注冊(cè)為單一實(shí)例且可以注入到任何服務(wù)生存期。

也就是說(shuō),在應(yīng)用啟動(dòng)前就已經(jīng)讀取配置文件生成對(duì)象(單一實(shí)例)。當(dāng)然,后續(xù)如果修改了配置文件(.json),也不會(huì)影響這個(gè)對(duì)象的。

3,IOptionsSnapshot

文檔解釋?zhuān)和ㄟ^(guò)使用 IOptionsSnapshot<TOptions>,針對(duì)請(qǐng)求生存期訪(fǎng)問(wèn)和緩存選項(xiàng)時(shí),每個(gè)請(qǐng)求都會(huì)計(jì)算一次選項(xiàng)。

IOptionsSnapshot 的生命作用域是 scoped ,在一個(gè)請(qǐng)求周期內(nèi)有效。

其它不變,使用時(shí):

        private readonly TestModel _options;
        public TestController(IOptionsSnapshot<TestModel> options)
        {
            _options = options.Value;
        }

由于 IOptionsSnapshot 每次請(qǐng)求都會(huì)進(jìn)行更新,因此配置文件變更后,可以及時(shí)獲得更新。

IOptionsMonitor 則略有不同:

    public class TestController : ControllerBase
    {
        private readonly IOptionsMonitor<TestModel> _options;
        public TestController(IOptionsMonitor<TestModel> options)
        {
            _options = options;
        }
        [HttpGet("T")]
        public ContentResult T()
        {

            return new ContentResult()
            {
                Content = _options.CurrentValue.Title
            };
        }
    }

IOptionsSnapshot 和 IOptionsMonitor 都可以檢測(cè)到配置文件的更改,但是 IOptionsSnapshot 每次請(qǐng)求都是一個(gè)新的對(duì)象,而 IOptionsMonitor 是單例模式。

到此這篇關(guān)于ASP.NET Core選項(xiàng)接口的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論