Cysharp / MessagePipe

High performance in-memory/distributed messaging pipeline for .NET and Unity.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

It's not really an issue, I was looking for help so I decided to ask here

olehmekhedok opened this issue · comments

Hello everyone,

I am trying to integrate MessagePipe into my project and I have a question:

whenever I want to use a new message I need to register it

builder.RegisterMessageBroker<TestMessage>();

It's kind of annoying, is it possible to configure in someway MessagePipe to be able to just use it without pre-registration? just like below:

GlobalMessagePipe.GetSubscriber<TestMessage>().Subscribe(message => Debug.Log("test " + message.Text));
GlobalMessagePipe.GetPublisher<TestMessage>().Publish(new TestMessage("Aaaaaaa"));

Thank you in advance.

Yes, you can create a more generic solution to avoid the need to register each message type manually. Here's one way to achieve this:

Create a static class called MessagePipeHelper that holds a dictionary of registered message types:

using System;
using System.Collections.Concurrent;
using MessagePipe;

public static class MessagePipeHelper
{
    private static ConcurrentDictionary<Type, object> _brokers = new ConcurrentDictionary<Type, object>();

    public static IMessagePublisher<TMessage> GetPublisher<TMessage>()
    {
        return ((MessageBroker<TMessage>)_brokers.GetOrAdd(typeof(TMessage), _ => new MessageBroker<TMessage>())).Publisher;
    }

    public static IMessageSubscriber<TMessage> GetSubscriber<TMessage>()
    {
        return ((MessageBroker<TMessage>)_brokers.GetOrAdd(typeof(TMessage), _ => new MessageBroker<TMessage>())).Subscriber;
    }
}

Now, you can use the MessagePipeHelper class to get a publisher or subscriber for any message type without needing to register it manually:
csharp

MessagePipeHelper.GetSubscriber<TestMessage>().Subscribe(message => Debug.Log("test " + message.Text));
MessagePipeHelper.GetPublisher<TestMessage>().Publish(new TestMessage("Aaaaaaa"));


This approach will automatically create and register a MessageBroker for each message type the first time it is requested, storing it in the _brokers dictionary for future use. This way, you don't need to manually register each message type, and the code will remain clean and concise.

Keep in mind that this approach does not use dependency injection for the MessageBroker instances, and it stores them statically in the MessagePipeHelper class. This could lead to some limitations if you have complex scoping requirements in your application. However, for simpler use cases, it should work just fine.

This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 30 days.