You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

InMemoryAgentRuntimeFixture.cs 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // InMemoryAgentRuntimeFixture.cs
  3. using System.Diagnostics;
  4. using Microsoft.AutoGen.Contracts;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.DependencyInjection.Extensions;
  7. using Microsoft.Extensions.Hosting;
  8. using AgentRegistration = (string Name, System.Type Type);
  9. namespace Microsoft.AutoGen.Core.Tests;
  10. /// <summary>
  11. /// InMemoryAgentRuntimeFixture - provides a fixture for the agent runtime.
  12. /// </summary>
  13. /// <remarks>
  14. /// This fixture is used to provide a runtime for the agent tests.
  15. /// However, it is shared between tests. So operations from one test can affect another.
  16. /// </remarks>
  17. public sealed class InMemoryAgentRuntimeFixture : IDisposable
  18. {
  19. private static IEnumerable<AgentRegistration> DefaultAgents = [(nameof(TestAgent), typeof(TestAgent))];
  20. public InMemoryAgentRuntimeFixture() : this(null, null)
  21. {
  22. }
  23. public InMemoryAgentRuntimeFixture(HostApplicationBuilder? hostBuilder = null, IEnumerable<AgentRegistration>? agentTypes = null)
  24. {
  25. var builder = hostBuilder ?? new HostApplicationBuilder();
  26. builder.Services.TryAddSingleton(DistributedContextPropagator.Current);
  27. builder.AddAgentWorker();
  28. foreach (var agentType in agentTypes ?? DefaultAgents)
  29. {
  30. builder.AddAgent(agentType.Name, agentType.Type);
  31. }
  32. AppHost = builder.Build();
  33. AppHost.StartAsync().Wait();
  34. }
  35. public IHost AppHost { get; }
  36. /// <summary>
  37. /// Start - starts the agent
  38. /// </summary>
  39. /// <returns>IAgentWorker, TestAgent</returns>
  40. public (IAgentRuntime, TestAgent) Start() => Start<TestAgent>();
  41. public (IAgentRuntime, TAgent) Start<TAgent>() where TAgent : Agent
  42. {
  43. var agent = ActivatorUtilities.CreateInstance<TAgent>(AppHost.Services);
  44. var worker = AppHost.Services.GetRequiredService<IAgentRuntime>();
  45. Agent.Initialize(worker, agent);
  46. return (worker, agent);
  47. }
  48. /// <summary>
  49. /// Stop - stops the agent and ensures cleanup
  50. /// </summary>
  51. public void Stop()
  52. {
  53. AppHost?.StopAsync().GetAwaiter().GetResult();
  54. }
  55. /// <summary>
  56. /// Dispose - Ensures cleanup after each test
  57. /// </summary>
  58. public void Dispose()
  59. {
  60. Stop();
  61. }
  62. }