A C# scoped message bus system that is lightweight, type safe and easy to use.
This is a single file library, place MessageBus/MessageBus.cs any where in your project.
Step #1 Declare your message types as delegates
public MyMessages
{
public delegate void LogText(string text);
}
The delegates can be in any class
Step #2 Create a function that will listen to the message
public MyListener
{
private void OnLogText(string text)
{
Console.WriteLine("Log " + text);
}
}
Step #3 Subscribe to the message
public MyListener
{
public MyListener()
{
MessageBus.Subscribe<MyMessages.LogText>(OnLogText);
}
private void OnLogText(string text)
{
Console.WriteLine("Log " + text);
}
}
Step #4 Dispatch messages
MessageBus.Dispatch<MyMessages.LogText>("Hello world!");
Step #5 Unsubscribe from messages
MessageBus.Unsubscribe<MyMessages.LogText>(OnLogText);
Subscriptions are kept as WeakReferences so if the subscriber gets finalized the subscription is automatically removed.
To subscribe to a scoped message bus, use a string for the scope
MessageBus.Subscribe<MyMessages.LogText>("scopeName", OnLogText);
To dispatch a message to a scooped bus
var dispatcher = MessageBus.GetDispatcher("scopeName");
dispatcher.Dispatch<MyMessages.LogText>("Hello scoped world!");
The MessageDispatcher can be used for dependency injection so the dispatcher fo messages doesn't need to know the scope