上一章 中,介绍了Options的注册,而在使用时只需要注入 IOption<T> 即可:

public ValuesController(IOptions<MyOptions> options)
{
var opt = options.Value;
}

本章就来详细介绍一下我们最熟悉的IOptions对象。

目录

  1. IOptions
  2. OptionsManager
  3. OptionsFactory
  4. OptionsCache
  5. IOptionsSnapshot

IOptions

IOptions 定义非常简单,只有一个Value属性:

public interface IOptions<out TOptions> where TOptions : class, new()
{
TOptions Value { get; }
}

上一章 中,我们知道它的默认实现为OptionsManager

    services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));

OptionsManager

OptionsManager 对options的创建和获取进行管理,我们先看一下它的源码:

public class OptionsManager<TOptions> : IOptions<TOptions>, IOptionsSnapshot<TOptions> where TOptions : class, new()
{
private readonly IOptionsFactory<TOptions> _factory;
private readonly OptionsCache<TOptions> _cache = new OptionsCache<TOptions>(); // Note: this is a private cache public OptionsManager(IOptionsFactory<TOptions> factory)
{
_factory = factory;
} public TOptions Value => Get(Options.DefaultName); public virtual TOptions Get(string name) => _cache.GetOrAdd(name, () => _factory.Create(name ?? Options.DefaultName));
}

如上,OptionsManager 的实现非常简单,使用IOptionsFactory来创建options对象,并使用内部属性OptionsCache<TOptions> _cache进行缓存。

OptionsFactory

IOptionsFactory 只定义了一个Create方法:

public interface IOptionsFactory<TOptions> where TOptions : class, new()
{
TOptions Create(string name);
}

其默认实现为:OptionsFactory

public class OptionsFactory<TOptions> : IOptionsFactory<TOptions> where TOptions : class, new()
{
private readonly IEnumerable<IConfigureOptions<TOptions>> _setups;
private readonly IEnumerable<IPostConfigureOptions<TOptions>> _postConfigures; public OptionsFactory(IEnumerable<IConfigureOptions<TOptions>> setups, IEnumerable<IPostConfigureOptions<TOptions>> postConfigures)
{
_setups = setups;
_postConfigures = postConfigures;
} public TOptions Create(string name)
{
var options = new TOptions();
foreach (var setup in _setups)
{
if (setup is IConfigureNamedOptions<TOptions> namedSetup)
{
namedSetup.Configure(name, options);
}
else if (name == Options.DefaultName)
{
setup.Configure(options);
}
}
foreach (var post in _postConfigures)
{
post.PostConfigure(name, options);
}
return options;
}
}

OptionsFactory的构造函数中注入了IConfigureOptions<>IPostConfigureOptions<>,也就是我们在 上一章 中介绍的 Configure 方法中所注册的配置,而这里使用了 IEnumerable 类型,则表示当注册多个时,为按顺序依次执行。

而我们在第一章中遇到的疑惑也豁然开朗,其Create方法,依次调用完Configure方法后,再调用PostConfigure方法,完成配置项的创建。

OptionsCache

OptionsCache 则是对字典的一个简单封装,就不再多说,直接看代码:

public class OptionsCache<TOptions> : IOptionsMonitorCache<TOptions> where TOptions : class
{
private readonly ConcurrentDictionary<string, Lazy<TOptions>> _cache = new ConcurrentDictionary<string, Lazy<TOptions>>(StringComparer.Ordinal); public void Clear() => _cache.Clear(); public virtual TOptions GetOrAdd(string name, Func<TOptions> createOptions)
{
name = name ?? Options.DefaultName;
return _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions)).Value;
} public virtual bool TryAdd(string name, TOptions options)
{
name = name ?? Options.DefaultName;
return _cache.TryAdd(name, new Lazy<TOptions>(() => options));
} public virtual bool TryRemove(string name)
{
name = name ?? Options.DefaultName;
return _cache.TryRemove(name, out var ignored);
}
}

IOptionsSnapshot

最后再来介绍一下 IOptionsSnapshot :

public interface IOptionsSnapshot<out TOptions> : IOptions<TOptions> where TOptions : class, new()
{
TOptions Get(string name);
}

看到Get方法的Name参数,我想大家便会想到在第一章中所介绍的指定NameConfigure方法,这便是它的用武之地了,通过Name的不同,可以配置同一个Options类型的多个实例。

IOptionsSnapshot的实现与IOptions一样,都是OptionsManager

services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));
services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>)));

通过如上代码,我们也可以发现它与IOptions还有一个本质的区别:IOptionsSnapshot注册的是Scoped类型,每一个请求中,都会创建一个新的OptionsManager对象。这样有什么好处呢?如果我们使用的是Action的方式配置的,那的确是没什么用,但是如果是使用IConfiguration配置的,则在我们修改了配置文件时,重新创建的Options会保持一致。

总结

本文描述了在 .NET Core Options 系统中IOptions的使用及实现原理。由于IOptions使用的是单例模式,因此当配置发生变化时,我们无法获取到最新的配置。而IOptionsSnapshot支持通过name来区分同一类型的不同 options ,并且每次请求都会重新创建 options 实例,相应的,会有稍微的性能损耗。如果我们希望能够监控配置源的变化,来自动更新,则可以使用下一章要介绍的更为强大的 IOptionsMonitor

ASP.NET Core 源码学习之 Options[2]:IOptions的更多相关文章

  1. ASP.NET Core 源码学习之 Options[1]:Configure

    配置的本质就是字符串的键值对,但是对于面向对象语言来说,能使用强类型的配置是何等的爽哉! 目录 ASP.NET Core 配置系统 强类型的 Options Configure 方法 源码解析 ASP ...

  2. ASP.NET Core 源码学习之 Options[4]:IOptionsMonitor

    前面我们讲到 IOptions 和 IOptionsSnapshot,他们两个最大的区别便是前者注册的是单例模式,后者注册的是 Scope 模式.而 IOptionsMonitor 则要求配置源必须是 ...

  3. ASP.NET Core 源码学习之 Options[3]:IOptionsSnapshot

    在 上一章 中,介绍了 IOptions 的使用, 而我们知道,在ConfigurationBuilder的AddJsonFile中,有一个reloadOnChange参数,设置为true时,在配置文 ...

  4. ASP.NET Core源码学习(一)Hosting

    ASP.NET Core源码的学习,我们从Hosting开始, Hosting的GitHub地址为:https://github.com/aspnet/Hosting.git 朋友们可以从以上链接克隆 ...

  5. ASP.NET Core 2.1 源码学习之 Options[2]:IOptions

    在 上一章 中,介绍了Options的注册,而在使用时只需要注入 IOption<T> 即可: public ValuesController(IOptions<MyOptions& ...

  6. ASP.NET Core 2.1 源码学习之 Options[2]:IOptions 【转】

    原文链接:https://www.cnblogs.com/RainingNight/p/strongly-typed-options-ioptions-in-asp-net-core.html 在 上 ...

  7. ASP.NET Core 源码学习之 Logging[2]:Configure

    在上一章中,我们对 ASP.NET Logging 系统做了一个整体的介绍,而在本章中则开始从最基本的配置开始,逐步深入到源码当中去. 默认配置 在 ASP.NET Core 2.0 中,对默认配置做 ...

  8. ASP.NET Core 源码学习之 Logging[1]:Introduction

    在ASP.NET 4.X中,我们通常使用 log4net, NLog 等来记录日志,但是当我们引用的一些第三方类库使用不同的日志框架时,就比较混乱了.而在 ASP.Net Core 中内置了日志系统, ...

  9. ASP.NET Core 源码学习之 Logging[3]:Logger

    上一章,我们介绍了日志的配置,在熟悉了配置之后,自然是要了解一下在应用程序中如何使用,而本章则从最基本的使用开始,逐步去了解去源码. LoggerFactory 我们可以在构造函数中注入 ILogge ...

随机推荐

  1. UserManager

    刚刚学习servlet,打算学做一个小项目把前边学到的知识做一个总结. 由于只是实现了一些简单的功能,所以美工就凑合着看吧(美工其实也不太会). 首先项目整体架构如图 项目准备工作: 要用到mysql ...

  2. 如何使用angular-ui的弹出框

    在开发项目时,我们经常性的会遇到弹出框的需求,例如登陆,注册,添加信息等等....面对这一需求,我们当然也可以使用自己的双手进行编写,如果你时间充足可以试试. 今天我们讲解一下如何在angular框架 ...

  3. Volley使用指南

    1.什么是Volley 在这之前,我们在程序中需要和网络通信的时候,大体使用的东西莫过于AsyncTaskLoader,HttpURLConnection,AsyncTask,HTTPClient(A ...

  4. 设计一个神经网络记住Or运算(日志一)

    由于公式书写太过麻烦,所以上传设计的手稿过程,为如下:

  5. Windows 随手笔记

    1.常见快捷方式 远程桌面 mstsc 注册表 regedit 组策略 gpedit.msc 2.Windows命令手册 ping命令 ping [-t] [-a] [-n count] [-l le ...

  6. [笔记]ACM笔记 - 排序小技巧

    Description 一个数组,要求先对前n个数字排序(以方便后续操作):又要求对前n+i个数字排序:又要求对前n+j - 前n+k个数字排序(i.j.k的大小远小于n,且i.j.k间没有大小关系) ...

  7. React入门---开始前的准备(下)-3

    React开始前的准备(下): ·配置webpack热加载(热加载就是修改js文件,点击保存之后,浏览器会自动刷新,提高开发效率) 1. 全局安装: npm install webpack -g np ...

  8. Word Ladder 2015年6月3日

    Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...

  9. swift pod第三方OC库使用use_frameworks!导致#import提示无法找到头文件

    以MBProgressHUD为例子 swift中Podfile文件一般都会加上use_frameworks! 这样就可以直接通过import MBProgressHUD来访问MBProgressHUD ...

  10. Http学习之使用HttpURLConnection发送post和get请求(3)

    使用HttpURLConnection发送post和get请求 但我们常常会碰到这样一种情况: 通过HttpURLConnection来模拟模拟用户登录Web服务器,服务器使用cookie进行用户认证 ...