前言

上一篇文章介绍IOptions的注册,本章我们继续往下看

IOptions

IOptions是一个接口里面只有一个Values属性,该接口通过OptionsManager实现


public interface IOptions<out TOptions> where TOptions : class, new()
{
/// <summary>
/// The default configured <typeparamref name="TOptions"/> instance
/// </summary>
TOptions Value { get; }
}

OptionsManager

OptionsManager实现了IOptions<>和IOptionsSnapshot<>,他使用内部属性OptionsCache 进行缓存操作;实现IOptionsSnapshot接口Get(string name)其实就是获取我们第一章所指定的Name,通过IOptionsFactory<>创建TOptions实例

    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 /// <summary>
/// Initializes a new instance with the specified options configurations.
/// </summary>
/// <param name="factory">The factory to use to create options.</param>
public OptionsManager(IOptionsFactory<TOptions> factory)
{
_factory = factory;
} /// <summary>
/// The default configured <typeparamref name="TOptions"/> instance, equivalent to Get(Options.DefaultName).
/// </summary>
public TOptions Value
{
get
{
return Get(Options.DefaultName);
}
} /// <summary>
/// Returns a configured <typeparamref name="TOptions"/> instance with the given <paramref name="name"/>.
/// </summary>
public virtual TOptions Get(string name)
{
name = name ?? Options.DefaultName; // Store the options in our instance cache
return _cache.GetOrAdd(name, () => _factory.Create(name));
}
} public interface IOptionsSnapshot<out TOptions> : IOptions<TOptions> where TOptions : class, new()
{
/// <summary>
/// Returns a configured <typeparamref name="TOptions"/> instance with the given name.
/// </summary>
TOptions Get(string name);
}

OptionsCache

OptionsCache采用了线程安全字典ConcurrentDictionary进行了封装用于内存缓存


public class OptionsCache<TOptions> : IOptionsMonitorCache<TOptions> where TOptions : class
{
private readonly ConcurrentDictionary<string, Lazy<TOptions>> _cache = new ConcurrentDictionary<string, Lazy<TOptions>>(StringComparer.Ordinal); /// <summary>
/// Clears all options instances from the cache.
/// </summary>
public void Clear() => _cache.Clear(); /// <summary>
/// Gets a named options instance, or adds a new instance created with <paramref name="createOptions"/>.
/// </summary>
/// <param name="name">The name of the options instance.</param>
/// <param name="createOptions">The func used to create the new instance.</param>
/// <returns>The options instance.</returns>
public virtual TOptions GetOrAdd(string name, Func<TOptions> createOptions)
{
if (createOptions == null)
{
throw new ArgumentNullException(nameof(createOptions));
}
name = name ?? Options.DefaultName;
return _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions)).Value;
} /// <summary>
/// Tries to adds a new option to the cache, will return false if the name already exists.
/// </summary>
/// <param name="name">The name of the options instance.</param>
/// <param name="options">The options instance.</param>
/// <returns>Whether anything was added.</returns>
public virtual bool TryAdd(string name, TOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
name = name ?? Options.DefaultName;
return _cache.TryAdd(name, new Lazy<TOptions>(() => options));
} /// <summary>
/// Try to remove an options instance.
/// </summary>
/// <param name="name">The name of the options instance.</param>
/// <returns>Whether anything was removed.</returns>
public virtual bool TryRemove(string name)
{
name = name ?? Options.DefaultName;
return _cache.TryRemove(name, out var ignored);
}
}

OptionsFactory

OptionsFactory实现了 IOptionsFactory.Create(string name);,

而OptionsFactory构造函数中注入了IConfigureOptions<>和IPostConfigureOptions<>,

这里使用了IEnumerable类型标识当注册多个时候按照次数依次的执行,从如下代码中我们也看到了我们在上一章中所说的Configures和postConfigures注册先后顺序问题。


public class OptionsFactory<TOptions> : IOptionsFactory<TOptions> where TOptions : class, new()
{
private readonly IEnumerable<IConfigureOptions<TOptions>> _setups;
private readonly IEnumerable<IPostConfigureOptions<TOptions>> _postConfigures;
private readonly IEnumerable<IValidateOptions<TOptions>> _validations; public OptionsFactory(IEnumerable<IConfigureOptions<TOptions>> setups, IEnumerable<IPostConfigureOptions<TOptions>> postConfigures) : this(setups, postConfigures, validations: null)
{ } public OptionsFactory(IEnumerable<IConfigureOptions<TOptions>> setups, IEnumerable<IPostConfigureOptions<TOptions>> postConfigures, IEnumerable<IValidateOptions<TOptions>> validations)
{
_setups = setups;
_postConfigures = postConfigures;
_validations = validations;
} 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);
} if (_validations != null)
{
var failures = new List<string>();
foreach (var validate in _validations)
{
var result = validate.Validate(name, options);
if (result.Failed)
{
failures.AddRange(result.Failures);
}
}
if (failures.Count > 0)
{
throw new OptionsValidationException(name, typeof(TOptions), failures);
}
} return options;
}
}

ASP.NET Core 选项模式源码学习Options IOptions(二)的更多相关文章

  1. ASP.NET Core 选项模式源码学习Options Configure(一)

    前言 ASP.NET Core 后我们的配置变得更加轻量级了,在ASP.NET Core中,配置模型得到了显著的扩展和增强,应用程序配置可以存储在多环境变量配置中,appsettings.json用户 ...

  2. ASP.NET Core 选项模式源码学习Options IOptionsMonitor(三)

    前言 IOptionsMonitor 是一种单一示例服务,可随时检索当前选项值,这在单一实例依赖项中尤其有用.IOptionsMonitor用于检索选项并管理TOption实例的选项通知, IOpti ...

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

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

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

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

  5. ASP.NET Core 2.1 源码学习之 Options[3]:IOptionsMonitor 【转】

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

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

    原文链接:https://www.cnblogs.com/RainingNight/p/strongly-typed-options-configure-in-asp-net-core.html 配置 ...

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

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

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

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

  9. .NET Core 2.1 源码学习:看 SocketsHttpHandler 如何在异步方法中连接 Socket

    在 .NET Core 2.1 中,System.Net.Sockets 的性能有了很大的提升,最好的证明是 Kestrel 与 HttpClient 都改为使用 System.Net.Sockets ...

随机推荐

  1. eclipse断点的使用---for循环举例

    在很多时候,我们在学习过程中,不知道代码具体的实现过程,很好奇这个变量的值怎么就发生的变化,用好断点的使用,帮助我们更好的理解. 例子:10以内的奇数之和 package day03; public ...

  2. python Tesseract安装方法

    python Tesseract安装方法 EXE可执行文件地址:http://download.csdn.net/download/whatday/7740469:下载tesseract-ocr-se ...

  3. egret常用功能

    egret常用功能<pre>//////////////////////////////////////////////////////////////////////////////// ...

  4. 自建yum仓库,该仓库为默认仓库

    YUM REPO: http://content.example.com/rhel7.0/x86_64/dvd 创建自建yum REPO文件: vim /etc/yum.repos.d/redhat. ...

  5. 前端与算法 leetcode 8. 字符串转换整数 (atoi)

    目录 # 前端与算法 leetcode 8. 字符串转换整数 (atoi) 题目描述 概要 提示 解析 解法一:正则 解法二:api 解法二:手搓一个api 算法 传入测试用例的运行结果 执行结果 G ...

  6. 《JAVA 程序员面试宝典(第四版)》之传递与引用篇

    废话开场白         这个周末突然很想创业,为什么呢?原因很简单,我周围的同学或者说玩的比较好的朋友都发达了,前一个月和一个两年前还睡在一张床上的朋友,他现在已经在深圳买房买车了,没错是在深圳买 ...

  7. python:爬虫0

    什么是网页爬虫,也叫网页蜘蛛.把互联网比作一个蜘蛛网,有好多节点,这个蜘蛛在网上爬来爬去,对对网页中的每个关键字进行建立索引,然后建立索引数据库,经过复杂的排序算法后,这些算法的结果将按照相关度的高低 ...

  8. HTML页面插入图片,使用background还是img标签

    很多新手在刚开始学习HTML标签的时候,老师一定会教你 <img src="xxx.png"/> 这种引入图片格式,第二天学习css的时候,老师又会教你给div等元素添 ...

  9. TensorFlow2.0极简安装(亲测有效)

    x相信每一个学习深度学习的人来说都知道Google的深度学习框架TensorFlow,估计每个人都想成为一个TF Boy(TensorFlow Boy).我也是这个想法,于是我踏上了安装TensorF ...

  10. python与redis交互及redis基本使用

    Redis简介 Redis是一使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日个开源的志型.Key-Value数据库,并提供多种语言的API. 从2010年3月15日起,Redis的开发工 ...