A Better Pub/Sub Messenger for .NET Applications with WeakReferenceMessenger

Поділитися
Вставка
  • Опубліковано 15 чер 2024
  • Sometimes you need to pass pieces of data to and from different parts of your application. This may be for communication between viewmodels or perhaps from your app startup class passing important information. With the .NET Community Toolkit you have a simple cross-platform way of sending and receiving messages no matter what type of app your are building. You can use it with .NET MAUI, WinUI, WPF, WinForms, ASP.NET Core, or just about any other .NET application!
    Toolkit Release Blog - devblogs.microsoft.com/dotnet...
    Documentation - docs.microsoft.com/dotnet/com...
    Community Toolkit on GitHub - github.com/CommunityToolkit/d...
    Sample Code: github.com/jamesmontemagno/To...
    Join this channel to get access to perks:
    / @jamesmontemagno
    👕 Buy some swag! - jamesmontemagno.myspreadshop....
    ☕️ Buy me a coffee - www.buymeacoffee.com/jamesmon...
    Follow:
    👨‍💻 GitHub: github.com/jamesmontemagno
    🦜 Twitter: / jamesmontemagno
    📄 Website: www.montemagno.com
    📰 Newsletter: newsletter.montemagno.com/
    Disclaimer: This channel, videos, and streams are created in my spare time and are a product of me... James Montemagno! They are NOT officially affiliated or endorsed by Microsoft (my employer) in any way. Opinions and views are my own.
    What is on my hat? It is the CLE clothing logo because I am from Cleveland! Checkout their awesome CLE merch: cleclothingco.myshopify.com/
    What is that art on my wall? It is an original piece from the French street artist Gregos of La Butte Montmartre: / bcez1onhiqx
    Chapters:
    00:00 - Why you need a messenger for apps
    01:30 - App and code overview
    03:40 - Adding CommunityToolkit.Mvvm
    04:00 - Creating a message to send
    06:05 - Subscribing to messages
    10:00 - Sending messages
    13:00 - Cleaner implementation with IRecipient
    15:05 - Wrap-up
    My Setup:
    📷 Canon M50 Mark II - amzn.to/3P8R7lp
    💡 Nanoleaf Elements Lights - amzn.to/3umwJVW
    🎙 Blue Spark Microphone - amzn.to/3qgtYkq
    🎙 Blue Pop Filter - amzn.to/3jEWM3r
    🤳 Rode Microphone Arm - amzn.to/2Z68AlE
    🎧 Sony MDR7306 Headphones - amzn.to/372jxta
    📲 Stream Deck - amzn.to/373Uk1n
    📹 Elgato Cam Link - amzn.to/3a9eGbh
    📷 GoPro Hero - amzn.to/374lm90
    🖱 MX Master 2S Mouse - amzn.to/3d7J2gj
    ⌨️ Tecware Phantom Keyboard - amzn.to/3aUP4y9
    #dotnet #dotnetmaui #aspnetcore
  • Наука та технологія

КОМЕНТАРІ • 112

  • @Henok-qn6nc
    @Henok-qn6nc Місяць тому

    Hey James , this is a really good tutorial !
    I followed your beginner series and have been having hard time to implement this myself.
    I think others may find this helpful, so it would be cool if you add it to the playlist as a final view
    Thanks for the video :)

  • @thomas.carney
    @thomas.carney Рік тому +4

    Great video! You really make it easy to understand how these things work. I was looking for how to use the old 'MessagingCenter' saw that it was deprecated, and then was like, "What the heck is this WeakReferenceMessenger??". Makes total sense now, thanks!

  • @Dazza_Doo
    @Dazza_Doo Рік тому

    Enjoying all your content: Love the Breakdown and Usage!
    I need a way of consistently using these toolkits in everyday code :D

  • @leszekjezierski9414
    @leszekjezierski9414 Рік тому +5

    Great stuff! 👍🏻 Looking forward to more Toolkit 8.0.0 goodies!

  • @ricardocosta1679
    @ricardocosta1679 Рік тому +6

    I learn a lot from your videos. I would like to see a video about background service with .NetMaui

  • @tegusolutions7154
    @tegusolutions7154 Рік тому +3

    Wow, good to see that Microsoft embraced this essential feature.
    I am looking forward to trying it out in a Blazor app, where the communication between the different components is a key feature.

  • @jeff-uq2sz
    @jeff-uq2sz 9 місяців тому

    As always, thank you! This has been supremely helpful!

  • @AndrewRiebe
    @AndrewRiebe Рік тому

    Thank you for getting to the point right away. Liked and subscribed!

  • @emmanueladebiyi2109
    @emmanueladebiyi2109 Рік тому +1

    This is super cool. Thanks James!

  • @alexpinkerton7459
    @alexpinkerton7459 Рік тому

    Wow! Wow! Wow! This is exactly what I'm looking for! Many thanks!

  • @SuperGulamali
    @SuperGulamali Рік тому

    Thank you James, Appreciate this!

  • @CodeProfessor
    @CodeProfessor Рік тому

    Awesome as always James!

  • @calin1996mh
    @calin1996mh Рік тому

    Thanks for the video, much better than the documentation!

  • @brendanalexander6053
    @brendanalexander6053 Рік тому +4

    Excellent James. Assume I could use this in a service, such as to listen to signalR pipeline messages. Then blast out messages within the app.

  • @maso4u
    @maso4u Рік тому +4

    I was scrambling all over the internet the last few days trying to understand how to actually use this feature on the toolkit... managed to understand a bit of the official documentation and its such a great feature, this video just helped me to further refine my usage of it.
    question though, I personally prefer having my commands in their own separate classes. Is there any way you'd recommend for me to go about it while making use of the mvvm toolkit?

  • @shahfaisal3923
    @shahfaisal3923 Рік тому

    Beautiful work

  • @rconn5641
    @rconn5641 Рік тому

    Awesome content. I appreciate all you do. I do have a question. I’ve looked some and I can’t find any guidance on proper use of weak vs strong reference. If the toolkit exposes an improper way to use something, it will be used improperly. Again I appreciate your content.

  • @CantonGregory
    @CantonGregory Рік тому +2

    Pretty cool to see this used. I think I would still prefer the reactive extensions package for some use cases.

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +2

      RX is my next exploration

    • @Sergio0694
      @Sergio0694 Рік тому

      You can actually use both! I'm also planning to investigate adding some IObservable APIs to the messenger types in the MVVM Toolkit, so one could easily get an observable representing a message subscription, to "bridge" the two worlds together and enable all sorts of other scenarios 🙂

  • @SoftwarePhilosophy
    @SoftwarePhilosophy Рік тому

    Was looking for this so much... We had EventAggregator in Prism which was missing on MAUI

  • @brianfisher100
    @brianfisher100 Рік тому +2

    Thanks

  • @jacanaro7641
    @jacanaro7641 Рік тому

    smooth pub sub, ty for sharing

  • @keigezellig
    @keigezellig 3 місяці тому

    Great video! A small question: What is the added value of using this ValueChangedMessage type because you can basically send any object of any type as a message.

  • @bluedark7724
    @bluedark7724 Рік тому

    Congrats on the 7 hour live stream.
    Unfortunately the docs don't click with me, I was also trying to understand how to use these Messages.
    I understand the concept of messages (subbing and unsubbing) from Unreal Engine.
    The toolkit is amazing, I don't know how to use it.

  • @eduhza
    @eduhza Рік тому

    You're the best!

  • @user-vg1ft2qf5i
    @user-vg1ft2qf5i 2 місяці тому

    Great video. Thanks! Is there a way to be a recipient of two or three different messages?

  • @user-wv1dw2ku9e
    @user-wv1dw2ku9e Рік тому

    잘보고 있습니다. 감사합니다.

  • @GuildOfCalamity
    @GuildOfCalamity Рік тому

    Your videos are great!
    Can you do a demo showing how to display local notifications on the phone using MAUI? (e.g. SnackBar)

  • @gwisekor
    @gwisekor Рік тому

    항상 고맙소

  • @amasoumi
    @amasoumi Рік тому

    great video!!

  • @johnatkins8012
    @johnatkins8012 Рік тому

    Thank you James. I just made use of this to pass a scanned QR Code value from a child ViewModel to its parent ViewModel, and it worked perfectly, updating the UI in the parent. Thanks also go to Gerald Versluis for his video about the ZXing scanning package.

  • @_rushas
    @_rushas 9 місяців тому

    Thanks for the video and great explanation. I just don't see in what scenario I would need to use the WeakReferenceMessenger in my application. Is it just to prevent the redundant code, or are there any other reasons to it? I mean I could have just put a RefreshList method on the page's OnAppear and I would get the main page content refreshed each time, so when I delete the item in other page I would still get the most recent collection when I navigate to my main page. So what is WeakReferenceMessenger good for?

  • @jeffm3865
    @jeffm3865 Рік тому

    Thanks for your great videos. When would one use query properties in shell vs the messenger you mention here? Sounds like they both have similar capabilities to pass messages between view models.

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      Depends. Like here I could have popped via “..” and then passed some info, but what if I’m not navigating you know

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      Just another tool in the toolbox

    • @sebastianbusek2087
      @sebastianbusek2087 Рік тому +1

      @@JamesMontemagno Also, an identifier wouldn't be enough, you would probably also need to pass a "command" argument which should identify an action to be triggered...

  • @andreasmersch6605
    @andreasmersch6605 Рік тому +1

    Very cool. And thanks for your videos. What about the garbage collector? Do I have to explicitly unregister subscriber?

    • @andreasmersch6605
      @andreasmersch6605 Рік тому

      RTFM. Sorry. StrongReferenceMessenger vs. WeakReferenceMessenger. 👍🏻

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      Strong ref yes, weak no as it is weak and will get collected

  • @franciscofernandezcasas7924

    Hello thanks for your amazing videos, I have a .NET MAUI question, I am having an issue with the .NET MAUI Entry, Editor and Picker controls, They show without Underline or Bottom line in MAUI, do you know how to fix this for all platforms

  • @logank.70
    @logank.70 Рік тому +2

    Question:
    For this to work do you need to make sure that A) when using a DI tool that your Weak/Strong reference messenger is a singleton and B) that the recipient view model is also some form of singleton?
    I know in my early days working with this pattern I would wonder why things weren't working and it was due to the DI tool creating a new instance of things when it would resolve the view model type. Can't send messages between two things if those two things have two different instances of the messenger. I'm sure the "Default" property is static and so it wouldn't be noticed. Maybe the view models could still suffer the same fate if not registered in DI properly?

    • @JamesMontemagno
      @JamesMontemagno  Рік тому

      For A for sure singleton as it is used through the app and is already a singleton. For B it shouldn’t matter. The recipient will go away when not needed and will unregister if weak ref

  • @aleksandrsmyk3397
    @aleksandrsmyk3397 Рік тому

    Its a Mediatr pattern out from the box. Its really useful

    • @marklnz
      @marklnz Рік тому

      Not quite "out of the box" exactly. I get that if you're using the Community Toolkit already it would make sense to give this a go over a dedicated implementation like MediatR, though.

    • @RealDieselMeister
      @RealDieselMeister Рік тому

      It's an simple Event or Message Dispatcher. Or others know that as EventAggregator or what ever. It's trivial and old.

  • @JohnMcDonagh-ih2zg
    @JohnMcDonagh-ih2zg Рік тому

    I might be wrong but I don't think you need to register it in constructor if you use IRecipient

  • @estevatopanchovillacruz9969
    @estevatopanchovillacruz9969 Рік тому +1

    awesome

  • @_rushas
    @_rushas 8 місяців тому

    I tried this today with pages that has transient dependency. Following this method had me trigger the same Receive method multiple times: say I enter to page and leave 5 times, if I trigger the Receive function; it will cause it to be triggered 5 times.

  • @ShahPrem20
    @ShahPrem20 Рік тому +1

    Hello James Thanks for awesome video
    Can you make video on following topic
    1. How can I implemented Jar binding in Maui.
    2. How can I design UI for different screen size in xaml

    • @emmanueladebiyi2109
      @emmanueladebiyi2109 Рік тому

      Check out official docs for creating Java Bindings. The experience is not awesome and I really hope it gets better but you should be able to get through it if you learn the ropes well enough. For responsive UI, OnIdiom is the magic word. Check out how to use it

  • @lukaskuchta1010
    @lukaskuchta1010 Рік тому

    Is there source generator varinat for this feature? Any attribut or something?

  • @aathifmahir
    @aathifmahir Рік тому

    James to Love to See a Video on Community Toolkit Messenger with DotNet Maui Dependency Injection, As Far as Community Toolkit Messenger Documentation there's no proper tutorial on implementing messenger with Dependency Injection, Love to see what you can regarding this

  • @sailorm79
    @sailorm79 Рік тому

    Channels. You are welcome.

  • @lucademarco5969
    @lucademarco5969 Рік тому +3

    What's the difference compared to Mediatr and why should I use Messenger instead? Thanks in advance!

    • @JamesMontemagno
      @JamesMontemagno  Рік тому

      Never used mediatr will check it out

    • @c0ward
      @c0ward Рік тому +1

      I use mediatr in my apps - works great.
      I'm not a fan of inheriting from classes for messages, so using IRequest and INotification to indicate a response or not are great, and I get to use [record] for all my messages rather than a class.

  • @lukaskuchta1010
    @lukaskuchta1010 Рік тому

    Why you used week manager? It is guaranteed that listener will not be randomly removed by by GC? It is safe used this week manager? Or what is the condition for removeng listneres from week variant?

    • @Moosa_Says
      @Moosa_Says Рік тому

      You don't need to Unregister weak references; they auto get collected by the GC. So, in case of registering weak reference messenger you don't need to manually unregister it.

  • @jdg2k6
    @jdg2k6 Рік тому

    Hey James, it is now October 2022. I’m coming from Xam forms world and just getting started with my evaluation and exploration of Maui. One of the first things I encountered was an article from Microsoft about NOT using toolkit. Something about all that code being absorbed into Maui. Can you elaborate on this? All the early Maui videos rave about the community toolkit but now it appears as if that package is deprecated.

    • @JamesMontemagno
      @JamesMontemagno  Рік тому

      There is a new toolkit for .net Maui, so you want to transition to that one

  • @mrsajjad30
    @mrsajjad30 Рік тому

    Please show us how to use TToken to send and receive messages

  • @younessesoft
    @younessesoft Рік тому

    i have a question plz i need respons if .net maui can execute ussd command if there any documentation for that i need that for my project plz tell me

  • @IcaroFelix2023
    @IcaroFelix2023 Місяць тому

    Would not it be better if you use Observables from System.Reactive ?

  • @paulegan3783
    @paulegan3783 Рік тому

    Thanks! Sorry if this is a daft question but how does this compare with subscribing to events? (E.g. performance diffs, convenience)

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      Events between components would be a tight coupling in this example and with a messenger like this they are losely coupled and also have weak references that can be garbage collected easier

    • @paulegan3783
      @paulegan3783 Рік тому

      @@JamesMontemagno Thanks!

  • @majesticjester1
    @majesticjester1 Рік тому +2

    Does not Maui already have MessagingCenter that does the same job?

    • @geraldlewis8221
      @geraldlewis8221 Рік тому

      Yes, but it's deprecated. It seems that it's something of a resource hog.

  • @gamertagsinryan
    @gamertagsinryan Рік тому

    How can I implement this in an asynchronous way?

  • @vintaatlanta6990
    @vintaatlanta6990 Рік тому

    How to explicitly unregister the recipients🧐

  • @konichiyyawa
    @konichiyyawa Рік тому +1

    how about a multiple IRecipient? seems like MessagingCenter Send and Subscribe right?

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      Yes!!! That is the goal to do multiple!! I think of this as messaging center replacement

    • @konichiyyawa
      @konichiyyawa Рік тому

      @@JamesMontemagno wow that's cool! it refactors my messaging center.

  • @harag9
    @harag9 Рік тому

    Thanks for showing this, but what happens if you're say 3 pages down and the first 2 pages are setup to listen for the delete message - when you delete the item on the 3rd page, will both pages get the command to delete?

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      Anyone that is subscribed would get the message correct so you should know who/what is subscribing to events.

    • @harag9
      @harag9 Рік тому

      @@JamesMontemagno Great thanks for confirming, thought that might be the case.

  • @thirumalk2
    @thirumalk2 Рік тому

    Hi it was very useful, I started my app migrate from Xamarin to .Net MAUI. I encounter few issues.
    1. In android TabbedPage is showing blank page after login page, MFA page and tabbed dashboard.
    2. Scroll view is not working when view loads and bing list cards from service. Page is not scrolling to show complete data loaded on page.
    3. Community toolkit pop up size is not adjusting based on content and even scroll is not working. Could you help me to resolve the issue.

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      Hard to help over comments on UA-cam. I would open issues in the respective github repo and try to create a new project to recreate something smaller.

  • @benjaminhilleriteau6868
    @benjaminhilleriteau6868 Рік тому

    What is the difference between this pub-sub messenger and the .net maui mesasging center ?

    • @JamesMontemagno
      @JamesMontemagno  Рік тому +1

      I would say that this is a much improved version over the built in one IMHO

  • @1mYse1LF
    @1mYse1LF Рік тому

    What kind of framework You using, what is that actually?
    You using visual studio code and C for android/mobile app? What about Android Studio?
    How it's working?

    • @JamesMontemagno
      @JamesMontemagno  Рік тому

      Check out all my videos on .NET MAUI! iOS android Mac and windows cross platform in c# with visual studio

  • @brandon-butler
    @brandon-butler Рік тому

    Your camera seems to be acting strangely. You can see banding moving across the background and the framerate seems low.

  • @ramigamal6637
    @ramigamal6637 10 місяців тому

    Awesome exploration, but in the minute 8:48 the r stands for the recipient not for the sender -_-

  • @richardlavallee6716
    @richardlavallee6716 Рік тому

    Thanks for the video. However, I am trying to register a message using a specific token and cannot find any information on it. All I can find is how to unregister using a token. If you don't mind, can you provide information on this. Thanks

    • @JamesMontemagno
      @JamesMontemagno  Рік тому

      I would suggest opening an issue on the projects GitHub page. That is usually the fastest

    • @richardlavallee6716
      @richardlavallee6716 Рік тому

      @@JamesMontemagno Thanks, but I finally figured it out for myself.

  • @tasher7882
    @tasher7882 Рік тому

    Video request: Media Picker (CapturePhotoAsync) with Winui3 patch fix.

  • @abdalarmden7382
    @abdalarmden7382 Рік тому

    how add event Click to ContentView in maui

    • @JamesMontemagno
      @JamesMontemagno  Рік тому

      I would add a TapGestureRecognizer for this :) it can be added to any view

  • @Any1SL
    @Any1SL Рік тому

    I wish Prism pub sub was available in all .net apps not just Wpf

  • @alfredocoindreau9876
    @alfredocoindreau9876 Рік тому

    Llevo 1.5 años en .net con c# y el manejo de James es tan alto que no entiendo la mitad de lo que escribe.

  • @abdalarmden7382
    @abdalarmden7382 Рік тому

    public event EventHandler Clicked;
    public event EventHandler Pressed;
    public event EventHandler Released;

  • @bramburn
    @bramburn Рік тому

    Thank you Jesus looking man 👞

    • @systemloc
      @systemloc 10 місяців тому

      I absolutely love the hair and beard. Pure eyecandy.

  • @MadaFakaTOO
    @MadaFakaTOO Рік тому +2

    This seems like an EventAggregator pattern with weak and strong references. It's nice but I don't see it being such a big deal.

  • @yevheniytymchishin8401
    @yevheniytymchishin8401 Рік тому

    I like Prism approach more.

    • @krccmsitp2884
      @krccmsitp2884 Рік тому

      Could you elaborate a bit on on that, please?

    • @yevheniytymchishin8401
      @yevheniytymchishin8401 Рік тому +2

      @@krccmsitp2884 yeah,
      1. Prism does not require to override the constructor when you define your Event (Message).
      2. When publish in Prism, you need just pass the payload (without explicit Event creation).
      3. In Prism you don't need to register the recipient when subscribe. Just specify the Event type and pass payload if required.

    • @krccmsitp2884
      @krccmsitp2884 Рік тому

      @@yevheniytymchishin8401 Thanks for your answer, it's been quite along time since I used Prism.
      1. You do not need to derive your message from ValueChangedMessage, the IMessenger implementations don't rely on it.
      2. You must, however, derive your messages from PubSubEvent to get the magic, IIRC.
      3. I don't see a conceptual difference between Subscribe() and Register(), after all you need to tell the messenger who will handle the message.

  • @yz777zhumabayev6
    @yz777zhumabayev6 Рік тому +1

    👍

  • @namelastname4077
    @namelastname4077 Рік тому

    I guess this would be too easy
    [ObservableProperty]
    [SendMessageOnMainThread(DeleteItemMessage)]
    private string deletedMessage;

  • @fayazvar3948
    @fayazvar3948 Рік тому

    What is this await GoBack(); does.

    • @munawarkhurshid1201
      @munawarkhurshid1201 Рік тому

      GoBack method is decorated with a relay command attribute. It is called when back button fires this command and I believe it takes you to the last page. I hope that helps.

    • @systemloc
      @systemloc 10 місяців тому

      It just navigates back to the previous page. When he clicks the Delete button, see how it leaves the detail page and goes back to the menu page

  • @Dazza_Doo
    @Dazza_Doo Рік тому

    Thanks