Skip to content
Merged
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
29 changes: 21 additions & 8 deletions src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,20 @@ public virtual TOptions GetOrAdd(string name, Func<TOptions> createOptions)
{
throw new ArgumentNullException(nameof(createOptions));
}

name = name ?? Options.DefaultName;
return _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions)).Value;
Lazy<TOptions> value;

#if NETCOREAPP
value = _cache.GetOrAdd(name, static (name, createOptions) => new Lazy<TOptions>(createOptions), createOptions);
#else
if (!_cache.TryGetValue(name, out value))
{
value = _cache.GetOrAdd(name, new Lazy<TOptions>(createOptions));
}
#endif

return value.Value;
}

/// <summary>
Expand All @@ -50,19 +62,20 @@ public virtual bool TryAdd(string name, TOptions options)
{
throw new ArgumentNullException(nameof(options));
}
name = name ?? Options.DefaultName;
return _cache.TryAdd(name, new Lazy<TOptions>(() => options));

return _cache.TryAdd(name ?? Options.DefaultName, new Lazy<TOptions>(
#if !NETCOREAPP
() =>
#endif
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 Lazy<TOptions> ignored);
}
public virtual bool TryRemove(string name) =>
_cache.TryRemove(name ?? Options.DefaultName, out _);
}
}