Interface ISubscriber<TMessage>
Interface representing subscribers to messages sent over a MessageBus. Classes wishing to respond to one or more message types as they are sent across the bus should implement this interface.
Namespace: GoRogue.Messaging
Assembly: GoRogue.dll
Syntax
public interface ISubscriber<in TMessage>
Type Parameters
Name | Description |
---|---|
TMessage | The type of message that the subscriber wants to handle. Any and all messages sent over the event bus you subscribe to that can cast to this type will be passed the Handle(TMessage) function when they are sent. |
Remarks
It is possible to have one class handle two different event types, by having it implement multiple ISubscriber types; however in this situation, you must either use the RegisterAllSubscribers<T>(T) method (or its "Try" variant) to register the subscriber, or call the RegisterSubscriber<TMessage>(ISubscriber<TMessage>) method once for each type of message the subscriber subscribes to (specifying the TMessage type manually each time). Although RegisterAllSubscribers will work for most use cases, when you want the fastest performance, you will want to prefer the RegisterSubscriber method, since RegisterAllSubscribers uses reflection.
class MultipleSubscriber : ISubscriber<string>, ISubscriber<string[]>
{
/* Explicit interface definitions are not required but are recommend for code clarity
void ISubscriber<string>.Handle(string message) => Console.WriteLine(message);
void ISubscriber<string[]>.Handle(string[] message) => Console.WriteLine(message.ExtendToString());
}
/* Later, when we add the subscriber to our message bus, we simply use the RegisterAllSubscribers method to ensure the subscriber is registered to both types. */
var messageBus = new MessageBus();
var multiSubber = new MultipleSubscriber();
messageBus.RegisterAllSubscribers(multiSubber);
Alternatively, we can use the RegisterSubscriber method to register the subscriber to each type individually.
/* Here, when we add the subscriber to our message bus, we add each subscriber interface separately */
var messageBus = new MessageBus();
var multiSubber = new MultipleSubscriber();
messageBus.RegisterSubscriber<string>(multiSubber);
messageBus.RegisterSubscriber<string[]>(multiSubber);
Methods
View SourceHandle(TMessage)
Function that should handle the specified type of message in whatever manner it needs to. Called automatically any time a message of the appropriate type is sent over an event bus this subscriber has been registered on.
Declaration
void Handle(TMessage message)
Parameters
Type | Name | Description |
---|---|---|
TMessage | message | Message that was sent. |