Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class OptionsCache<[DynamicallyAccessedMembers(Options.DynamicallyAccesse
IOptionsMonitorCache<TOptions>
where TOptions : class
{
private readonly ConcurrentDictionary<string, Lazy<TOptions>> _cache = new ConcurrentDictionary<string, Lazy<TOptions>>(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, Lazy<TOptions>> _cache = new ConcurrentDictionary<string, Lazy<TOptions>>(concurrencyLevel: 1, capacity: 31, StringComparer.Ordinal); // 31 == default capacity

/// <summary>
/// Clears all options instances from the cache.
Expand All @@ -38,6 +38,24 @@ public virtual TOptions GetOrAdd(string name, Func<TOptions> createOptions)
return _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions)).Value;
}

/// <summary>
/// Gets a named options instance, if available.
/// </summary>
/// <param name="name">The name of the options instance.</param>
/// <param name="options">The options instance.</param>
/// <returns>true if the options were retrieved; otherwise, false.</returns>
internal bool TryGetValue(string name, out TOptions options)
{
if (_cache.TryGetValue(name ?? Options.DefaultName, out Lazy<TOptions> lazy))
{
options = lazy.Value;
return true;
}

options = default;
return false;
}

/// <summary>
/// Tries to adds a new option to the cache, will return false if the name already exists.
/// </summary>
Expand Down
19 changes: 10 additions & 9 deletions src/libraries/Microsoft.Extensions.Options/src/OptionsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,7 @@ public OptionsManager(IOptionsFactory<TOptions> factory)
/// <summary>
/// The default configured <typeparamref name="TOptions"/> instance, equivalent to Get(Options.DefaultName).
/// </summary>
public TOptions Value
{
get
{
return Get(Options.DefaultName);
}
}
public TOptions Value => Get(Options.DefaultName);

/// <summary>
/// Returns a configured <typeparamref name="TOptions"/> instance with the given <paramref name="name"/>.
Expand All @@ -44,8 +38,15 @@ public virtual TOptions Get(string name)
{
name = name ?? Options.DefaultName;

// Store the options in our instance cache
return _cache.GetOrAdd(name, () => _factory.Create(name));
if (!_cache.TryGetValue(name, out TOptions options))
{
// Store the options in our instance cache. Avoid closure on fast path by storing state into scoped locals.
IOptionsFactory<TOptions> localFactory = _factory;
string localName = name;
options = _cache.GetOrAdd(name, () => localFactory.Create(localName));
}

return options;
}
}
}