diff --git a/zero/Communication/Messages/MessageAggregator.cs b/zero/Communication/Messages/MessageAggregator.cs index cd6a3f37..2ffb3c2a 100644 --- a/zero/Communication/Messages/MessageAggregator.cs +++ b/zero/Communication/Messages/MessageAggregator.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.Linq.Expressions; namespace zero.Communication; @@ -26,6 +27,13 @@ public class MessageAggregator : IMessageAggregator } + /// + public void Subscribe(Expression> handle) where TMessage : class, IMessage + { + Subscription.Add(new InlineMessageSubscription(handle)); + } + + /// public void Activate() where TMessage : class, IMessage @@ -43,6 +51,11 @@ public interface IMessageAggregator /// Task Publish(TMessage message) where TMessage : class, IMessage; + /// + /// Subscribe to a message + /// + void Subscribe(Expression> handle) where TMessage : class, IMessage; + /// /// Subscribes the specified handler to the spified message type /// diff --git a/zero/Communication/Messages/MessageSubscription.cs b/zero/Communication/Messages/MessageSubscription.cs index 3698f175..203825fb 100644 --- a/zero/Communication/Messages/MessageSubscription.cs +++ b/zero/Communication/Messages/MessageSubscription.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.DependencyInjection; +using System.Linq.Expressions; using System.Reflection; namespace zero.Communication; @@ -33,6 +34,38 @@ internal class MessageSubscription : IMessageSubscrip } +internal class InlineMessageSubscription : IMessageSubscription + where TMessage : class, IMessage +{ + private Expression> _handler; + + public InlineMessageSubscription(Expression> handler) + { + _handler = handler; + } + + + public bool CanDeliver() + { + return typeof(TMessage).GetTypeInfo().IsAssignableFrom(typeof(T)); + } + + public async Task Deliver(IServiceProvider serviceProvider, object message) + { + if (message == null) + { + throw new ArgumentNullException(nameof(message)); + } + if (!(message is TMessage)) + { + throw new ArgumentException($"{nameof(message)} must be of type '{typeof(TMessage).FullName}'"); + } + + await _handler.Compile()((TMessage)message); + } +} + + public interface IMessageSubscription { bool CanDeliver();