How to receive messages in a .Net 6 static class using the Community Toolkit Messenger

204 Views Asked by At

I'm using the Microsoft Community Toolkit's default Messenger to send messages between modules in my program and it works great - until I try to receive a message in a static class.

  • I can't make the class derive from ObservableRecipient because it is static.
  • I can't implement IRecipient because it is static.
  • I can't use WeakReferenceManager.Default.Register(this, (r, m) => MsgHandler(m)) because I can't use "this" in a static class.
  • WeakReferenceMessenger.Default.Register(ClassName.handler, (r, m) => handler(m.newStat)) compiles okay, but "handler" doesn't get called when the message is sent.

I've been struggling through the Microsoft Learn pages about Messenger and Register, but I don't know enough to be able to follow the descriptions. (These particular pages seem to be written by experts for experts, and I'm not expert (or smart) enough to figure out what they are talking about.)

My question is: Can a static class receive messages (seems very likely), and if so, what syntax do I have to use to register? It must be some variation of the last example above, but I haven't yet been able to figure out what it would be.

Thanks.

2

There are 2 best solutions below

1
iStuart On

I've just started to change my app from using event and EventHandler to WeakReferenceMessenger and encountered the same situation with a static class. My solution is to use

typeof(classname), (r, m) =>

instead of

this, (r, m) =>

and the lambda is called as expected.

A similar solution is to define a variable called me at the top of the class as as:

private static readonly Type me = typeof(classname);

then use

me, (r, m) =>
0
Markus On

iStuart's answer is actually exactly right. If you like it a bit more complete, here is a short example:

static void YourStaticMethod()
{
    WeakReferenceMessenger.Default.Register<MyMessage>(typeof(classname), (recipient, message) =>
    {
        // handle message here...
    });
}

instead of:

static void YourStaticMethod()
{
    WeakReferenceMessenger.Default.Register<MyMessage>(this, (recipient, message) =>
    {
        // handle message here...
    });
}

So you only have to replace "this" with "typeof(classname)".