.NET: Update AgentFeatureCollections with feedback (#2379)

* Update AgentFeatureCollections with feedback

* Address feedback.

* Fix issue with sample.

* Change generic type restriction to notnull

* Remove revision

* Update dotnet/src/Microsoft.Agents.AI.Abstractions/Features/AgentFeatureCollectionExtensions.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Add revision back again and improve some formatting.

* Remove virtual from revision.

* Add overloads taking type as param and add unit tests.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
westey
2025-11-24 10:57:49 +00:00
committed by GitHub
Unverified
parent 570bed9ff6
commit 9d86adfcb2
9 changed files with 308 additions and 158 deletions
@@ -118,9 +118,8 @@ async Task CustomChatMessageStore_UsingFactoryAndExistingExternalId_Async()
// It's possible to create a new thread that uses the same chat message store id by providing
// the VectorChatMessageStoreThreadDbKeyFeature in the feature collection when creating the new thread.
AgentFeatureCollection features = new();
features.Set(new VectorChatMessageStoreThreadDbKeyFeature(messageStoreFromFactory.ThreadDbKey!));
AgentThread resumedThread = agent.GetNewThread(features);
AgentThread resumedThread = agent.GetNewThread(
new AgentFeatureCollection().WithFeature(new VectorChatMessageStoreThreadDbKeyFeature(messageStoreFromFactory.ThreadDbKey!)));
// Run the agent with the thread that stores conversation history in the vector store.
Console.WriteLine(await agent.RunAsync("Now tell the same joke in the voice of a pirate, and add some emojis to the joke.", resumedThread));
@@ -149,9 +148,7 @@ async Task CustomChatMessageStore_PerThread_Async()
// We can then pass the feature collection when creating a new thread.
// We also have the opportunity here to pass any id that we want for storing the chat history in the vector store.
VectorChatMessageStore perThreadMessageStore = new(vectorStore, "chat-history-1");
AgentFeatureCollection features = new();
features.Set<ChatMessageStore>(perThreadMessageStore);
AgentThread thread = agent.GetNewThread(features);
AgentThread thread = agent.GetNewThread(new AgentFeatureCollection().WithFeature<ChatMessageStore>(perThreadMessageStore));
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread));
@@ -191,10 +188,13 @@ async Task CustomChatMessageStore_PerRun_Async()
// If the agent doesn't support a message store, it would be ignored.
// We also have the opportunity here to pass any id that we want for storing the chat history in the vector store.
VectorChatMessageStore perRunMessageStore = new(vectorStore, "chat-history-1");
AgentFeatureCollection features = new();
features.Set<ChatMessageStore>(perRunMessageStore);
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread, options: new AgentRunOptions() { Features = features }));
Console.WriteLine(await agent.RunAsync(
"Tell me a joke about a pirate.",
thread,
options: new AgentRunOptions()
{
Features = new AgentFeatureCollection().WithFeature<ChatMessageStore>(perRunMessageStore)
}));
// When serializing this thread, we'll see that it has no messagestore state, since the messagestore was not attached to the thread,
// but just provided for the single run. Note that, depending on the circumstances, the thread may still contain other state, e.g. Memories,
@@ -237,8 +237,9 @@ namespace SampleApp
// or finally we can generate one ourselves.
this.ThreadDbKey = serializedStoreState.ValueKind is JsonValueKind.String
? serializedStoreState.Deserialize<string>()
: features?.Get<VectorChatMessageStoreThreadDbKeyFeature>()?.ThreadDbKey
?? Guid.NewGuid().ToString("N");
: features?.TryGet<VectorChatMessageStoreThreadDbKeyFeature>(out var threadDbKeyFeature) is true
? threadDbKeyFeature.ThreadDbKey
: Guid.NewGuid().ToString("N");
}
public string? ThreadDbKey { get; }
@@ -55,7 +55,12 @@ internal sealed class A2AAgent : AIAgent
/// <inheritdoc/>
public sealed override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
=> new A2AAgentThread() { ContextId = featureCollection?.Get<ConversationIdAgentFeature>()?.ConversationId };
=> new A2AAgentThread()
{
ContextId = featureCollection?.TryGet<ConversationIdAgentFeature>(out var conversationIdFeature) is true
? conversationIdFeature.ConversationId
: null
};
/// <summary>
/// Get a new <see cref="AgentThread"/> instance using an existing context id, to continue that conversation.
@@ -4,6 +4,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Shared.Diagnostics;
@@ -18,9 +19,7 @@ namespace Microsoft.Agents.AI;
[DebuggerTypeProxy(typeof(FeatureCollectionDebugView))]
public class AgentFeatureCollection : IAgentFeatureCollection
{
private static readonly KeyComparer s_featureKeyComparer = new();
private readonly IAgentFeatureCollection? _defaults;
private readonly int _initialCapacity;
private readonly IAgentFeatureCollection? _innerCollection;
private Dictionary<Type, object>? _features;
private volatile int _containerRevision;
@@ -39,59 +38,38 @@ public class AgentFeatureCollection : IAgentFeatureCollection
public AgentFeatureCollection(int initialCapacity)
{
Throw.IfLessThan(initialCapacity, 0);
this._initialCapacity = initialCapacity;
this._features = new(initialCapacity);
}
/// <summary>
/// Initializes a new instance of <see cref="AgentFeatureCollection"/> with the specified defaults.
/// Initializes a new instance of <see cref="AgentFeatureCollection"/> with the specified inner collection.
/// </summary>
/// <param name="defaults">The feature defaults.</param>
public AgentFeatureCollection(IAgentFeatureCollection defaults)
/// <param name="innerCollection">The inner collection.</param>
/// <remarks>
/// <para>
/// When providing an inner collection, and if a feature is not found in this collection,
/// an attempt will be made to retrieve it from the inner collection as a fallback.
/// </para>
/// <para>
/// The <see cref="Remove{TFeature}"/> method will only remove features from this collection
/// and not from the inner collection. When removing a feature from this collection, and
/// it exists in the inner collection, it will still be retrievable from the inner collection.
/// </para>
/// </remarks>
public AgentFeatureCollection(IAgentFeatureCollection innerCollection)
{
this._defaults = defaults;
this._innerCollection = Throw.IfNull(innerCollection);
}
/// <inheritdoc />
public virtual int Revision
public int Revision
{
get { return this._containerRevision + (this._defaults?.Revision ?? 0); }
get { return this._containerRevision + (this._innerCollection?.Revision ?? 0); }
}
/// <inheritdoc />
public bool IsReadOnly { get { return false; } }
/// <inheritdoc />
public object? this[Type key]
{
get
{
Throw.IfNull(key);
return this._features != null && this._features.TryGetValue(key, out var result) ? result : this._defaults?[key];
}
set
{
Throw.IfNull(key);
if (value == null)
{
if (this._features?.Remove(key) is true)
{
this._containerRevision++;
}
return;
}
if (this._features == null)
{
this._features = new Dictionary<Type, object>(this._initialCapacity);
}
this._features[key] = value;
this._containerRevision++;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
@@ -100,63 +78,102 @@ public class AgentFeatureCollection : IAgentFeatureCollection
/// <inheritdoc />
public IEnumerator<KeyValuePair<Type, object>> GetEnumerator()
{
if (this._features != null)
if (this._features is not { Count: > 0 })
{
foreach (var pair in this._features)
{
yield return pair;
}
IEnumerable<KeyValuePair<Type, object>> e = ((IEnumerable<KeyValuePair<Type, object>>?)this._innerCollection) ?? [];
return e.GetEnumerator();
}
if (this._defaults != null)
if (this._innerCollection is null)
{
// Don't return features masked by the wrapper.
foreach (var pair in this._features == null ? this._defaults : this._defaults.Except(this._features, s_featureKeyComparer))
return this._features.GetEnumerator();
}
if (this._innerCollection is AgentFeatureCollection innerCollection && innerCollection._features is not { Count: > 0 })
{
return this._features.GetEnumerator();
}
return YieldAll();
IEnumerator<KeyValuePair<Type, object>> YieldAll()
{
HashSet<Type> set = [];
foreach (var entry in this._features)
{
yield return pair;
set.Add(entry.Key);
yield return entry;
}
foreach (var entry in this._innerCollection.Where(x => !set.Contains(x.Key)))
{
yield return entry;
}
}
}
/// <inheritdoc />
public TFeature? Get<TFeature>()
public bool TryGet<TFeature>([MaybeNullWhen(false)] out TFeature feature)
where TFeature : notnull
{
if (typeof(TFeature).IsValueType)
if (this.TryGet(typeof(TFeature), out var obj))
{
var feature = this[typeof(TFeature)];
if (feature is null && Nullable.GetUnderlyingType(typeof(TFeature)) is null)
{
throw new InvalidOperationException(
$"{typeof(TFeature).FullName} does not exist in the feature collection " +
$"and because it is a struct the method can't return null. Use 'AgentFeatureCollection[typeof({typeof(TFeature).FullName})] is not null' to check if the feature exists.");
}
return (TFeature?)feature;
feature = (TFeature)obj;
return true;
}
return (TFeature?)this[typeof(TFeature)];
feature = default;
return false;
}
/// <inheritdoc />
public void Set<TFeature>(TFeature? instance)
public bool TryGet(Type type, [MaybeNullWhen(false)] out object feature)
{
this[typeof(TFeature)] = instance;
if (this._features?.TryGetValue(type, out var obj) is true)
{
feature = obj;
return true;
}
if (this._innerCollection?.TryGet(type, out var defaultFeature) is true)
{
feature = defaultFeature;
return true;
}
feature = default;
return false;
}
/// <inheritdoc />
public void Set<TFeature>(TFeature instance)
where TFeature : notnull
{
Throw.IfNull(instance);
this._features ??= new();
this._features[typeof(TFeature)] = instance;
this._containerRevision++;
}
/// <inheritdoc />
public void Remove<TFeature>()
where TFeature : notnull
=> this.Remove(typeof(TFeature));
/// <inheritdoc />
public void Remove(Type type)
{
if (this._features?.Remove(type) is true)
{
this._containerRevision++;
}
}
// Used by the debugger. Count over enumerable is required to get the correct value.
private int GetCount() => this.Count();
private sealed class KeyComparer : IEqualityComparer<KeyValuePair<Type, object>>
{
public bool Equals(KeyValuePair<Type, object> x, KeyValuePair<Type, object> y)
{
return x.Key.Equals(y.Key);
}
public int GetHashCode(KeyValuePair<Type, object> obj)
{
return obj.Key.GetHashCode();
}
}
private sealed class FeatureCollectionDebugView(AgentFeatureCollection features)
{
private readonly AgentFeatureCollection _features = features;
@@ -0,0 +1,23 @@
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Agents.AI;
/// <summary>
/// Extension methods for <see cref="IAgentFeatureCollection"/>.
/// </summary>
public static class AgentFeatureCollectionExtensions
{
/// <summary>
/// Adds the specified feature to the collection and returns the collection.
/// </summary>
/// <typeparam name="TFeature">The feature key.</typeparam>
/// <param name="features">The feature collection to add the new feature to.</param>
/// <param name="feature">The feature to add to the collection.</param>
/// <returns>The updated collection.</returns>
public static IAgentFeatureCollection WithFeature<TFeature>(this IAgentFeatureCollection features, TFeature feature)
where TFeature : notnull
{
features.Set(feature);
return features;
}
}
@@ -8,7 +8,7 @@ namespace Microsoft.Agents.AI;
/// An agent feature that allows providing a conversation identifier.
/// </summary>
/// <remarks>
/// This feature allows a user to provide a specific identifier for chat history whether stored in the underlying AI service or stored in a 3rd party store.
/// This feature allows a user to provide a specific identifier for chat history when stored in the underlying AI service.
/// </remarks>
public class ConversationIdAgentFeature
{
@@ -16,7 +16,7 @@ public class ConversationIdAgentFeature
/// Initializes a new instance of the <see cref="ConversationIdAgentFeature"/> class with the specified thread
/// identifier.
/// </summary>
/// <param name="conversationId">The unique identifier of the thread required by the underlying AI service or 3rd party store. Cannot be <see langword="null"/> or empty.</param>
/// <param name="conversationId">The unique identifier of the thread required by the underlying AI service. Cannot be <see langword="null"/> or empty.</param>
public ConversationIdAgentFeature(string conversationId)
{
this.ConversationId = Throw.IfNullOrWhitespace(conversationId);
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Agents.AI;
@@ -24,23 +25,48 @@ public interface IAgentFeatureCollection : IEnumerable<KeyValuePair<Type, object
int Revision { get; }
/// <summary>
/// Gets or sets a given feature. Setting a null value removes the feature.
/// Attempts to retrieve a feature of the specified type.
/// </summary>
/// <param name="key"></param>
/// <returns>The requested feature, or null if it is not present.</returns>
object? this[Type key] { get; set; }
/// <typeparam name="TFeature">The type of the feature to retrieve.</typeparam>
/// <param name="feature">When this method returns, contains the feature of type <typeparamref name="TFeature"/> if found; otherwise, the
/// default value for the type.</param>
/// <returns>
/// <see langword="true"/> if the feature of type <typeparamref name="TFeature"/> was successfully retrieved;
/// otherwise, <see langword="false"/>.
/// </returns>
bool TryGet<TFeature>([MaybeNullWhen(false)] out TFeature feature)
where TFeature : notnull;
/// <summary>
/// Retrieves the requested feature from the collection.
/// Attempts to retrieve a feature of the specified type.
/// </summary>
/// <param name="type">The type of the feature to get.</param>
/// <param name="feature">When this method returns, contains the feature of type <paramref name="type"/> if found; otherwise, the
/// default value for the type.</param>
/// <returns>
/// <see langword="true"/> if the feature of type <paramref name="type"/> was successfully retrieved;
/// otherwise, <see langword="false"/>.
/// </returns>
bool TryGet(Type type, [MaybeNullWhen(false)] out object feature);
/// <summary>
/// Remove a feature from the collection.
/// </summary>
/// <typeparam name="TFeature">The feature key.</typeparam>
/// <returns>The requested feature, or null if it is not present.</returns>
TFeature? Get<TFeature>();
void Remove<TFeature>()
where TFeature : notnull;
/// <summary>
/// Remove a feature from the collection.
/// </summary>
/// <param name="type">The type of the feature to remove.</param>
void Remove(Type type);
/// <summary>
/// Sets the given feature in the collection.
/// </summary>
/// <typeparam name="TFeature">The feature key.</typeparam>
/// <param name="instance">The feature value.</param>
void Set<TFeature>(TFeature? instance);
void Set<TFeature>(TFeature instance)
where TFeature : notnull;
}
@@ -43,7 +43,12 @@ public class CopilotStudioAgent : AIAgent
/// <inheritdoc/>
public sealed override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
=> new CopilotStudioAgentThread() { ConversationId = featureCollection?.Get<ConversationIdAgentFeature>()?.ConversationId };
=> new CopilotStudioAgentThread()
{
ConversationId = featureCollection?.TryGet<ConversationIdAgentFeature>(out var conversationIdFeature) is true
? conversationIdFeature.ConversationId
: null
};
/// <summary>
/// Get a new <see cref="AgentThread"/> instance using an existing conversation id, to continue that conversation.
@@ -289,13 +289,17 @@ public sealed partial class ChatClientAgent : AIAgent
public override AgentThread GetNewThread(IAgentFeatureCollection? featureCollection = null)
=> new ChatClientAgentThread
{
ConversationId = featureCollection?.Get<ConversationIdAgentFeature>()?.ConversationId,
ConversationId = featureCollection?.TryGet<ConversationIdAgentFeature>(out var conversationIdAgentFeature) is true
? conversationIdAgentFeature.ConversationId
: null,
MessageStore =
featureCollection?.Get<ChatMessageStore>()
?? this._agentOptions?.ChatMessageStoreFactory?.Invoke(new() { SerializedState = default, Features = featureCollection, JsonSerializerOptions = null }),
featureCollection?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true
? chatMessageStoreFeature
: this._agentOptions?.ChatMessageStoreFactory?.Invoke(new() { SerializedState = default, Features = featureCollection, JsonSerializerOptions = null }),
AIContextProvider =
featureCollection?.Get<AIContextProvider>()
?? this._agentOptions?.AIContextProviderFactory?.Invoke(new() { SerializedState = default, Features = featureCollection, JsonSerializerOptions = null })
featureCollection?.TryGet<AIContextProvider>(out var aIContextProviderFeature) is true
? aIContextProviderFeature
: this._agentOptions?.AIContextProviderFactory?.Invoke(new() { SerializedState = default, Features = featureCollection, JsonSerializerOptions = null })
};
/// <summary>
@@ -353,17 +357,15 @@ public sealed partial class ChatClientAgent : AIAgent
/// <inheritdoc/>
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null, IAgentFeatureCollection? featureCollection = null)
{
var chatMessageStoreFeature = featureCollection?.Get<ChatMessageStore>();
Func<JsonElement, JsonSerializerOptions?, ChatMessageStore>? chatMessageStoreFactory =
chatMessageStoreFeature is not null
featureCollection?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true
? (jse, jso) => chatMessageStoreFeature
: this._agentOptions?.ChatMessageStoreFactory is not null
? (jse, jso) => this._agentOptions.ChatMessageStoreFactory.Invoke(new() { SerializedState = jse, Features = featureCollection, JsonSerializerOptions = jso })
: null;
var aiContextProviderFeature = featureCollection?.Get<AIContextProvider>();
Func<JsonElement, JsonSerializerOptions?, AIContextProvider>? aiContextProviderFactory =
aiContextProviderFeature is not null
featureCollection?.TryGet<AIContextProvider>(out var aiContextProviderFeature) is true
? (jse, jso) => aiContextProviderFeature
: this._agentOptions?.AIContextProviderFactory is not null
? (jse, jso) => this._agentOptions.AIContextProviderFactory.Invoke(new() { SerializedState = jse, Features = featureCollection, JsonSerializerOptions = jso })
@@ -644,7 +646,7 @@ public sealed partial class ChatClientAgent : AIAgent
// If the caller provided an override message store via run options, we should use that instead of the message store
// on the thread.
if (runOptions?.Features?.Get<ChatMessageStore>() is ChatMessageStore chatMessageStoreFeature)
if (runOptions?.Features?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true)
{
messageStore = chatMessageStoreFeature;
}
@@ -745,7 +747,7 @@ public sealed partial class ChatClientAgent : AIAgent
// If the caller provided an override message store via run options, we should use that instead of the message store
// on the thread.
if (runOptions?.Features?.Get<ChatMessageStore>() is ChatMessageStore chatMessageStoreFeature)
if (runOptions?.Features?.TryGet<ChatMessageStore>(out var chatMessageStoreFeature) is true)
{
messageStore = chatMessageStoreFeature;
}
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Linq;
namespace Microsoft.Agents.AI.Abstractions.UnitTests;
@@ -10,98 +11,168 @@ namespace Microsoft.Agents.AI.Abstractions.UnitTests;
public class AgentFeatureCollectionTests
{
[Fact]
public void AddedInterfaceIsReturned()
public void Feature_RoundTrips()
{
// Arrange.
var interfaces = new AgentFeatureCollection();
var thing = new Thing();
interfaces[typeof(IThing)] = thing;
// Act.
interfaces.Set<IThing>(thing);
Assert.True(interfaces.TryGet<IThing>(out var actualThing));
var thing2 = interfaces[typeof(IThing)];
Assert.Equal(thing2, thing);
// Assert.
Assert.Same(actualThing, thing);
Assert.Equal(1, interfaces.Revision);
}
[Fact]
public void IndexerAlsoAddsItems()
public void RemoveOfT_Removes()
{
// Arrange.
var interfaces = new AgentFeatureCollection();
var thing = new Thing();
interfaces[typeof(IThing)] = thing;
interfaces.Set<IThing>(thing);
Assert.True(interfaces.TryGet<IThing>(out _));
Assert.Equal(interfaces[typeof(IThing)], thing);
// Act.
interfaces.Remove<IThing>();
// Assert.
Assert.False(interfaces.TryGet<IThing>(out _));
Assert.Equal(2, interfaces.Revision);
}
[Fact]
public void SetNullValueRemoves()
public void Remove_Removes()
{
// Arrange.
var interfaces = new AgentFeatureCollection();
var thing = new Thing();
interfaces[typeof(IThing)] = thing;
Assert.Equal(interfaces[typeof(IThing)], thing);
interfaces.Set<IThing>(thing);
Assert.True(interfaces.TryGet<IThing>(out _));
interfaces[typeof(IThing)] = null;
// Act.
interfaces.Remove(typeof(IThing));
var thing2 = interfaces[typeof(IThing)];
Assert.Null(thing2);
// Assert.
Assert.False(interfaces.TryGet<IThing>(out _));
Assert.Equal(2, interfaces.Revision);
}
[Fact]
public void GetMissingStructFeatureThrows()
public void TryGetMissingFeature_ReturnsFalse()
{
// Arrange.
var interfaces = new AgentFeatureCollection();
var ex = Assert.Throws<InvalidOperationException>(() => interfaces.Get<int>());
Assert.Equal("System.Int32 does not exist in the feature collection and because it is a struct the method can't return null. Use 'AgentFeatureCollection[typeof(System.Int32)] is not null' to check if the feature exists.", ex.Message);
// Act & Assert.
Assert.False(interfaces.TryGet<Thing>(out var actualThing));
Assert.Null(actualThing);
}
[Fact]
public void GetMissingFeatureReturnsNull()
public void Set_Null_Throws()
{
// Arrange.
var interfaces = new AgentFeatureCollection();
Assert.Null(interfaces.Get<Thing>());
// Act & Assert.
Assert.Throws<ArgumentNullException>(() => interfaces.Set<IThing>(null!));
}
[Fact]
public void GetStructFeature()
public void IsReadOnly_DefaultsToFalse()
{
// Arrange.
var interfaces = new AgentFeatureCollection();
const int Value = 20;
interfaces.Set(Value);
Assert.Equal(Value, interfaces.Get<int>());
// Act & Assert.
Assert.False(interfaces.IsReadOnly);
}
[Fact]
public void GetNullableStructFeatureWhenSetWithNonNullableStruct()
public void TryGetOfT_FallsBackToInnerCollection()
{
var interfaces = new AgentFeatureCollection();
const int Value = 20;
interfaces.Set(Value);
Assert.Null(interfaces.Get<int?>());
}
[Fact]
public void GetNullableStructFeatureWhenSetWithNullableStruct()
{
var interfaces = new AgentFeatureCollection();
const int Value = 20;
interfaces.Set<int?>(Value);
Assert.Equal(Value, interfaces.Get<int?>());
}
[Fact]
public void GetFeature()
{
var interfaces = new AgentFeatureCollection();
// Arrange.
var inner = new AgentFeatureCollection();
var thing = new Thing();
interfaces.Set(thing);
inner.Set<IThing>(thing);
var outer = new AgentFeatureCollection(inner);
Assert.Equal(thing, interfaces.Get<Thing>());
// Act & Assert.
Assert.True(outer.TryGet<IThing>(out var actualThing));
Assert.Same(actualThing, thing);
}
[Fact]
public void TryGetOfT_OverridesInnerWithOuterCollection()
{
// Arrange.
var inner = new AgentFeatureCollection();
var innerThing = new Thing();
inner.Set<IThing>(innerThing);
var outer = new AgentFeatureCollection(inner);
var outerThing = new Thing();
outer.Set<IThing>(outerThing);
// Act & Assert.
Assert.True(outer.TryGet<IThing>(out var actualThing));
Assert.Same(outerThing, actualThing);
}
[Fact]
public void TryGet_FallsBackToInnerCollection()
{
// Arrange.
var inner = new AgentFeatureCollection();
var thing = new Thing();
inner.Set<IThing>(thing);
var outer = new AgentFeatureCollection(inner);
// Act & Assert.
Assert.True(outer.TryGet(typeof(IThing), out var actualThing));
Assert.Same(actualThing, thing);
}
[Fact]
public void TryGet_OverridesInnerWithOuterCollection()
{
// Arrange.
var inner = new AgentFeatureCollection();
var innerThing = new Thing();
inner.Set<IThing>(innerThing);
var outer = new AgentFeatureCollection(inner);
var outerThing = new Thing();
outer.Set<IThing>(outerThing);
// Act & Assert.
Assert.True(outer.TryGet(typeof(IThing), out var actualThing));
Assert.Same(outerThing, actualThing);
}
[Fact]
public void Enumerate_OverridesInnerWithOuterCollection()
{
// Arrange.
var inner = new AgentFeatureCollection();
var innerThing = new Thing();
inner.Set<IThing>(innerThing);
var outer = new AgentFeatureCollection(inner);
var outerThing = new Thing();
outer.Set<IThing>(outerThing);
// Act.
var items = outer.ToList();
// Assert.
Assert.Single(items);
Assert.Same(outerThing, items.First().Value as IThing);
}
private interface IThing