diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandle.cs b/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandle.cs new file mode 100644 index 000000000..c86e73dea --- /dev/null +++ b/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandle.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// IHandle.cs + +using Google.Protobuf; + +namespace Microsoft.AutoGen.Core.Python; + +/// +/// Defines a handler interface for processing items of type . +/// +/// The type of item to be handled, which must implement . +public interface IHandle where T : IMessage +{ + /// + /// Handles the specified item asynchronously. + /// + /// The item to be handled. + /// A task that represents the asynchronous operation. + Task Handle(T item, CancellationToken cancellationToken = default); +} + +public interface IHandle where InT : IMessage where OutT : IMessage +{ + /// + /// Handles the specified item asynchronously. + /// + /// The item to be handled. + /// A task that represents the asynchronous operation. + Task Handle(InT item, CancellationToken cancellationToken = default); +} diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandleExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandleExtensions.cs new file mode 100644 index 000000000..5053e5965 --- /dev/null +++ b/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandleExtensions.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// IHandleExtensions.cs + +using System.Reflection; + +namespace Microsoft.AutoGen.Core.Python; + +/// +/// Provides extension methods for types implementing the IHandle interface. +/// +public static class IHandleExtensions +{ + /// + /// Gets all the handler methods from the interfaces implemented by the specified type. + /// + /// The type to get the handler methods from. + /// An array of MethodInfo objects representing the handler methods. + public static MethodInfo[] GetHandlers(this Type type) + { + var handlers = type.GetInterfaces().Where(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IHandle<>) || i.GetGenericTypeDefinition() == typeof(IHandle<,>))); + return handlers.SelectMany(h => h.GetMethods().Where(m => m.Name == "Handle")).ToArray(); + } + + /// + /// Gets a lookup table of handler methods from the interfaces implemented by the specified type. + /// + /// The type to get the handler methods from. + /// A dictionary where the key is the generic type and the value is the MethodInfo of the handler method. + public static Dictionary GetHandlersLookupTable(this Type type) + { + var handlers = type.GetHandlers(); + return handlers.ToDictionary(h => + { + var generic = h.DeclaringType!.GetGenericArguments(); + return generic[0]; + }); + } +}