Last active
March 5, 2022 07:12
-
-
Save SteveDunn/a03953236e08c4818cd992dc0101aa23 to your computer and use it in GitHub Desktop.
In response to an .NET Runtime API request (https://github.com/dotnet/runtime/issues/62112), The proposal was for a way to use _either_ the default values in a list, **or** the values bound from configuration. This simple gist shows an alternative, that is simply a custom `ICollection`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using Microsoft.Extensions.Configuration; | |
var builder = new ConfigurationBuilder() | |
.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile("appsettings.json", optional: false); | |
var options = new MyImageProcessingOptions(); | |
var config = builder.Build(); | |
config.Bind("MyImageProcessingOptions", options); | |
Console.WriteLine(string.Join(",", options.ResizeWidths)); | |
public class MyImageProcessingOptions | |
{ | |
public DefaultableCollection<int> ResizeWidths { get; } = new(100, 200, 400, 800); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DefaultableCollection<T> : ICollection<T> | |
{ | |
private readonly List<T> _items; | |
private bool _overridden; | |
public DefaultableCollection(params T[] defaults) => _items = defaults.ToList(); | |
public void Add(T value) | |
{ | |
if (!_overridden) | |
{ | |
_overridden = true; | |
_items.Clear(); | |
} | |
_items.Add(value); | |
} | |
public void Clear() => _items.Clear(); | |
public bool Contains(T item) => _items.Contains(item); | |
public void CopyTo(T[] array, int arrayIndex) => _items.CopyTo(array, arrayIndex); | |
public bool Remove(T item) => _items.Remove(item); | |
public int Count => _items.Count; | |
public bool IsReadOnly => false; | |
public IEnumerator<T> GetEnumerator() => _items.GetEnumerator(); | |
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"MyImageProcessingOptions": { | |
"ResizeWidths": [ | |
"42", | |
"69", | |
"666" | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment