And for those wondering, there is an Rx video coming. The approach in the end is just one example of a safe and easy alternative. Not a goto for everything event related.
I've been using Rx for a couple years now and really like it, especially for lots of async I/O calls. The big challenges are: 1) In the java ecosystem blocking threads is a basic assumption, including specifications like servlet and jdbc. 2) Its a really different way of thinking. Since everything is immutable even things like loops go away! Kotlin, but i think most will get the gist: Flux.interval(Duration.ofSeconds(1)) .map { object { val guid = UUID.randomUUID() val time = LocalTime.now() } } .doOnNext { println(it.guid) } .filter { it.time.second % 5 == 0 } .doOnNext { println(it.time) } .take(10) .subscribe()
In Unity, event driven architecture is very useful to reduce dependencies between various components, such as UI, managers, controllers etc. It is also one way to prevent the use of Singletons.
Highly recommend implementing a message broker / mediator into a Unity project to allow communication between systems without the need to be depdendent on one another.
@@Artmos I hate doing any referencing in the inspector since that will make debugging VERY HARD and annoying in bigger projects... You cannot see in a feasible way whether some function is called, asset referenced etc. That is why Atoms is a no-go but UniRx might be nice.
@@Haapavuo I think that's personal preference. I really like having my components decoupled by using ScriptableObjects. I guess if you don't like that, another solution could be a dependency injection library.
Nice try! But no way, Nick, you just replace Observer pattern with Mediator (some simple kind of), and say - Events are deprecated. Built-in events mechanism allows to implement push and pull notification strategies, and in case of complex systems you have to mark your classes with redundant INotificationHandler + memory traffic is probably bigger. So, there is space for discussion here, but not for loud sounds sort of "Events are deprecated". So personally for me - don't worth it. And thanks for nice content, anyway. Keep coding.
Events is a built-in observer pattern. Similar to IEnumerable (Iterator pattern, but implemented, actually better than officially described by GoF). My imho.
I agree. Events have and ever will have their place in the .Net world. They are fast, lightweight, easy to use. If one doesn't understand why an object gets captured in a lambda, then pulling a blown up nuget package and introducing tons of micro classes with dependencies to that nuget package won't help them either
@@jonathandunn9302 I mean he did specifically say in the video that the context of the video is backend services, not front-end work like WinForms and UIs etc.
This is another one of those .... "Don't use XXX ... it causes so many problems!!!" .... where XXX can be nulls or event etc etc. I have to say I'm struggling to remember the last time I had issues using events ... in the same way I don't think I've had problems with nulls. I know I'm becoming quite an old dog now but I'd really like to stick with my events for as long as I can. Thanks for the video.
Event in C# is very powefull but alot of pple didnt know how to use it correct. Try to define the event as static and subscribe on constructor everytime. And you can use EventHandler instead of eventsarg object
May this video should have been named : "Benefits of using MEDIATR for events handling." Instead you ask a question ? I'm ok to give my opinion : With MEDIATR, it just seems that the Handlers are instanciated each time so that, their constructor param which is TransientService, will just be reinstanciated before being injected. No magic here, this is just a MEDIATR mechanism of reinstanciating handlers here. Thanks for showing this MEDIATR feature but for me this is absolutely not excluding the native events feature benefits.
My issue with Mediatr notifications is that the default implementation runs all the events synchronously and if one of them throws an exception the rest fail to execute. Jimmy Bogard has documentation on how to implement a different handler. It may be worth doing a video on.
You are spoiling my videos! 😂 yes the events run sequentially (not synchronously) so what you’re saying is true. There is a way around it and there is another alternative too which I’m planning to make a video on
Pretty much an almost flawless approach to replacing events in modern apps. But I wanted to see what could be a flaw with this approach. The only thing I can think of that this doesn't do in a simple way is unsubscribing from the notification. Since MediatR uses DI to find the handlers, they are automatically subscribed by class signature. A way to remedy this I think is to create a optional method on a new INotificationHandler: Task ShouldSubscribeAsync(); This method is automatically called upon registration or lazily during runtime, and based on the result, either keeps or deregisters that notification handler instance for that scoped resolution of that request. Singleton would invoke this method once, transient for every request, etc. Otherwise, I feel like you have to manually deregister the dependency based on the result of the method in the early stages of the application which shouldn't have this type of logic if you are going for a clean architecture and separation of concerns. What do you guys think?
There's really no way to get around events when programming for games, where there are so many individual systems running (for instance AI/NPC) as well as player input and possibly multiplayer/server input. Also when working with speech recognizers, the recognizer isn't predictable if the speech is continuous, so events will be necessary to collect the results as they trickle in. One could set up ones own polling mechanisms but they tend to be a lot less sophisticated when created from within something like C# (i.e. no interop) than the stuff perfected by framework library creators over the course of many years. The top layer of event design should be handled by you of course, but under the hood there can be a lot of elaborate stuff going on to make events less expensive and just slicker, like hooking up to system interrupts or sniffing other events to start the polling, or up its frequency, only when logically necessary.
Год назад+1
Events are a crucial part in several domains, Component based programming for example. Here is demonstrated that in a specific domain (Web handlers) they are better alternatives. Event here it is still debatable, since handlers are created and disposed for every notification. You may want this in some case, but perhaps you don't in some others
Video used to have a sponsor and the write line was saying “Thanks ”, but I decided to not go with them so I blurred it. That’s why my website call-out is from another video too
I have been enjoying Observable for a while, between Reactive Extentions, Reative UI, etc. I also enjoy F#. From what I recall, in F# events can be subscribed to as observables.
I expected him to talk about observables are they are actually that are evening used to replace events. Mediatr isn’t really comptable at all. It’s just a hidden factor Service calling back into the ioc container on each invocation… that’s easy to do on your of if that’s what you want but it has nothing to do with the events.
@@mwwhited I think I agree with you. But also might be whether or not we are talking about "Events" or "events" (IYKWIM). My preference for "events" at the moment is MassTransit. I think an "event sourcing system"* that works by registering a series of Observable Subscriptions (or even just Observable pipelines, because then you can return something, which could be handled like a Task await on the "Other End" would be very cool). * Referring to Mediatr and MassTransit, this probably has an actual name, but I don't know it :P.
Really important to note here: we're talking about a captured lambda or function, not about a capturing lambda or function. Big difference. The event is capturing its handler functions, which if they capture any transient service objects, they both remain cached.
I agree with the sentiment expressed a lot here, in the sense that I don't think you sufficiently expressed why events should be deprecated. Your original architecture is flawed, and replacing one publisher-subscribed mechanism for another observer pattern really doesn't make that much of a difference, except for the handlers apparently being newed-up on every invocation with MediatR (which I believe will be a significant expanse of your architecture design). If you truly want to get rid of events as much as possible, you should switch to Reactive Extensions, which is a proper way to handle data streams.
When you are writing "Hello World", you do not really need events. You can use a mediator or not. Once you start writing something meaningful, you use something like BackgroundWorker or SerialPort or other dotnet APIs, which fire events. Once you go beyond junior level, you start working on larger projects and work with third party libraries written in other languages with COM interfaces, or do tricky stuff with operating system components. They fire C# events.
I work in larger distributed systems and MediaR is just fine for decoupling certain aspects of your business layer. No need for other 3rd party libraries or COM interfaces when a simple pub/sub model is needed.
This is a clever alternative but what is the performance difference for expensive event handlers. It seems that Mediator would create and destroy the objects for every call.
But that’s fine because you want proper scoping. The risk of closure in the event handler approach is way more dangerous because it won’t be just slow it will also capture dependencies and cause bugs
2 года назад+3
People are often worried about DI having to have to create many objects and that being slow or taking too much memory. In reality, if you for example have a C# class with some logic and say 4 dependencies (some injected services), the resulting piece of memory allocated for that object is really just 4 pointers to the dependencies. Now compare that to a foreach that creates an iterator and causes about the same. But somehow people don't think about that.
@ If it's transient then it's constantly reallocating those 4 dependencies, if it's an iterator then it's just allocated once.
2 года назад+1
@@ShadoFXPerino yes but the point I am trying to make is that people are not rational in this regard and somehow fear this one allocation of the transient object. The same people then go on and create a monster Linq in some hot spot method of some Singleton. In my opinion it is a good price to pay for having the scoping clearly handled.
@ You are very correct on that irrational obsession, and I'll admit, I have probably obsessed just like that on more than one occasion. However, I think the impact this could have on the garbage collector when you subscribe with many handlers can be a valid concern. Of course, then your main problem is just that you think you have too many handlers, but if you subscribe with stateless objects, like most services, then you can argue that this is waste... Though I wonder, if there is an "INotificationHandler" interface, then maybe there also exists something like an "INotificationStateless" interface from which objects would be put in a singleton.
Thank you for great video as always. 16:18 : I expect to have the same Guid over and over because Trainsient services follow the lifetime of its injector. Since TickerService is Singleton and even not its injector (BackgroundService) is a singleton, TransientService injected into TickerService will not be disposed until TickerService is disposed. And whenever the event methods are called it will use same TransientService. And the same instance of TransientService will have the same guid which is assigned once. I personally do not see a problem with event system here. I agree that MediatR is a modern approach and very flexible. However this is a bit missleading.
The only way this would work without passing the factory of the service down would be to create a new class every time. It’s bad and I actually do events a service of not showing how bad it can really get. The feature itself isn’t bad obviously, but people (and I invite you to check on GitHub) get it more wrong than right
I completly agree, if TickerService would want to new instance on every call, It would need to have a somewhat factory for TransientService, not an instance itself.
Can't you just workaround this by resolving the service every time with the IServiceProvider interface instead of injecting it into the singleton?. Nice video as always btw
You didn't mention that `event` can be used with any delegate type. I usually just do `event Action`. I don't find the object sender to be of much use outside of specific UI frameworks.
Microsoft guidelines recommends using EventHandler for events. Also the reference to the sender is quite useful during debugging if your subscriber handles messages from couple producers.
11:09 This feels a lot like a pretty common DI issue and it's usually solved with factories. Autofac will resolve Func to a factory for transient service to allow you to do what you're talking about. Getting the ID would then look like _transientServiceFactory().Id which would create a new instance on each tick as desired.
Hey Nick, I'm a bit confused about the GUID issue. If you're requesting transient services from the BackgroundService shouldn't you inject the ServiceProvider and then get a new scope and resolve services every tick? Wouldn't that give a new GUID?
Injecting the ServiceProvider is an anti pattern called service locator. It should be avoided because you never know what services will be resolved if you do that
@@nickchapsas MediatR is really just a wrapper around a service locator. If you are using Microsoft DI it is the service provider that it is calling in the end is it not?
@@RENAUDADAM service locator pattern is an anti pattern which should be avoided in most use cases, but if you are building frameworks (such as mediator) then it can be okay, but using it as a normal way of pulling "magic" dependencies out of thin air into a class should be avoided, it makes your code hard to test. It goes against the dependency inversion principal.
@@RENAUDADAM sure but it’s not MY service locator. I don’t know about any of it and nothing in my application knows about it either. There is a big difference there. Dictionary.ContainsKey uses gotos. That doesn’t mean that I would use gotos
@@nickchapsas great video man! I have a question, sorry i don't have much experience. If i want a new viewmodel for example so it has to be "empty" or as its initial state, how do i get one without saying new() or the service provider? For example the user switches between some views and everytime they have to be resetted..
@@nickchapsas My point was that events should not be used in the same circumstances as mediator notifications, but events and callbacks can. If I were to create something like the FileSystemWatcher, using mediator would be a bizarre implementation. Also, it would be fun if libraries started to implement events as mediator notifications and disagreed on what version or library to use.
@@EspenSkaufel Ofc they are not the same, I never said they are, but the Notifications implementation of MediatR can give you an argueably better alternative for this usecase. Ofc you would not use MediatR for the usecase you mentioned. An observer pattern would be way better here. Events can be used to implement callbacks. Notifications can be used to implement events. Events as a concept is the root, not the end. Event he callbacks you mention aren't events. They are just callbacks triggers by something. That something can be events but it can be something else too.
@@nickchapsas Sorry for being annoying, bad habit. Your title triggered the response, as I expect to see developers trying to avoid using events at all costs after watching this. Knowing when to use what is why experience matters in software development. Just like with inheritance, it is bad most times, good sometimes 🥴.
Sorry, not convinced at all. Your expected result which I would sum up as: 1. Handler of event without "memory", new instance every time. 2. async calling. It's not "default" setting for events, but still it's very easy to make them work that way. With simpler code in which you see the behavior. If I see code, which looks like some plain old class with injected dependensy to some service, and for some strange reason this class is instanced every time, I woud not call this code good. You could get the same result with just simple factory or get returning new instance change. Like one line of code and you know -> Ok, I will get new guid every time I use it. As for the async you have full control with events over how and when event would fire. You can filter subs, you can fire them sync, you can use tasks, queues and bilion other things with that. async handler isn't always a way do it. To sum up, question. Let change your example. I want it to write those guids on some file -> poor man simplest log.
Events are not the most intuitive things to create. One thing I've sometimes used them for is cross thread communication, but in doing so you may also need to marshal to the other thread, since normally the thread that fires the event, also does the listener work.
Implementing async events really isn’t that much work, you can just use delegates and task with event handlers and it ends up working quite nicely, I’m surprised there isn’t for support/documentation on async events as in certain use case there very powerful
just to make sure. Does this mean that a new instance of every eventhandler (class that inherits from INotificationHandler) is created each time that event of type T happens?
I wrote something, inspired by Aurelia, called EventAggregator that is this same thing. It has been easy to test functionality that only happens when an event is published too. It's been tough since the team I'm currently working with is stuck on events but are slowly starting to see how easy event aggregation is to use in comparison to wiring events all over the place. Plus...you can have two things working together without needing to know of each other's existence. Both components have a dependency on IEventAggregator that ties them together. Just like with anything event related...have to make sure you clean up after yourself and unsubscribe from events when they aren't needed any longer. I'm a big fan of this approach to domain events.
Object modularity vs dependency injection. If you'd have went back to Y2K and told them you're going to reinstantiate every object for every tick they'd call you a nutjob. Then we had global internet, gigs of ram, stagnating CPU clock rates, and 32-core CPUs and it didn't sound so stupid anymore.
11:59 Unrelated, but I was curious about why I often see types being passed into methods to mark an Assembly for scanning? Why not pass in the actual Assembly object, possibly obtained from Assembly.GetExecutingAssembly() ? Or is is purely for consistency, if the Assembly you want to refer to is not the current executing assembly, so instead you pass in a type from the aseembly you intended to target?
So at 15:00 where you're passing in the instance of the transient service via DI... does this mean MediatR is constructing/allocating a new instance of EverySecondHandler each time that event is fired?
Amazing video as always. Just to clarify, Events/Observer and the Mediator pattern solve two different problems. In the former, you are interested in WHAT happened as well as WHO emitted that event. In the later, you are interested in WHAT happened but not always WHO emitted that event. The coupling is also different, in the Event/observer pattern, the subscriber should know the existence of the publisher, whereas in the Mediator pattern, the publisher doesn't know the existence of the subscriber and the subscriber doesn't know the existence of the publisher. Event/Observer are ideal for things like GUI or specialized services, whereas mediator is well suited for application wide communication.
You shouldn't be mixing events and observer. They are different things. Events can be used to implement the observer pattern but the observer pattern doesn't need events to be implemented.
@@nickchapsas Of course. I was just implying that c# events are just syntactic sugar for the ol' gang of four observer pattern.
Месяц назад
An IDisposable object that exposes events should always assign null to the events on disposal to prevent memory leaks. UI programming would be very difficult without events.
This is just an EventAggregator, which have existed for a long time. If you're writing WPF apps, then this stuff is no brainer though I still prefer events because it is much cleaner and I will always know the source of the event.
How do I run this Api in Visual Studio 2022 ver 17.8.6 and see a Console output? Using minimal APi with no swagger, auth or https. Only options i see is http, IIS Express and WSL...
When you’re using the built in events. The handler is listening for events from a specific instance. How would you accomplish the same thing using mediatr eventhandlers? For example if you have two instances of TickerBackgroundService running but you only want events from one of them?
I got an application in blazor build around events. Events only make sense around state. Since backend is 90% statelless then you may never need events.
Looks like something from Java to me. You have an observer/listener pattern with a mediator. I think it's good for application or system wide events as it only adds dependencies to the mediator. But for local messages C# events are better. A lot less code and slightly better performance.
I do like this approach better because there are other memory allocation issues if you don't set things up properly with your event subscriptions and unsubscriptions in a more traditional publisher/subscriber model.
Hello, i just don't get it, who instantiating EverySecondHandler and EveryFiveSecondHandler? They just defined in cs file and no instantiation happened
This video completely dropped the ball. Madiatr not only mixes command and query with notifications, it also is a terrible implementation of command snd query since it unifies both into one irequest interface. Not only could you implement it better yourself in 5 minutes since command and query basically consists of just a handful of interfaces, videos like this, claiming this is somehow more modern than c# events are exactly the reason I've seen code bases overengineered and wannabe architects using mediatr for all application communication when 90% of it is synchronous. DONT implement solutions before you run into a problem. I HATE this "I found a new library, now I'll use it everywhere and claim this is the state of the art way of doing things, feeling smart". I like your videos but please be aware that videos like this are regularly used by shitty developers to make the project hell for their colleagues. Libraries are tools. They should be used where appropriate. Vlaiminb things like "this is how it's done nowadays" is massively damaging.
Sry, for this maybe "stupid" question, but if you attach the eventHandler in the constructor then how you detach the eventHandler, if the object is destroyed? Do you have to overwrite the destruct constructor (~TickerService)? Or what will be best solution?
no need, since when tickerservice is collected also its methods are collected. you do need to be wary of events and eventhandlers though, in other cases you could cause a memory leak
Not really a stupid question at all, and hits at the root of the problem. The difference between the two models is who 'owns' what. In the older event model the event handler is responsible for doing the work. The event pulls in the objects it needs, and then does the work. The object itself has no idea what might happen to it, which can be a problem if that object might want to do something that those closures need to know about (such as being disposed of, or switched out). In the publishing model data is pushed to objects, and the event has no idea what might be done with that data. The major difference is that the object definitely knows about event handler, and so can definitely send messages back to it. 2 way communication is possible, and basic functionality can be available by default (such as dependency injection, or disposal). Unfortunately there is no general answer to what an event closure should do in the case of disposal of one of it's dependencies, but defaulting to disposing itself (and informing it's other dependencies it has done so) seems reasonable. It is inherently a 2 way communication problem. Standard events are a lightweight solution where we know that one way communication is sufficient, but for anything above the lowest levels it usually isn't. How you extend it to a 2 way system is a more complicated problem, and I'm not qualified to post an opinion on what the 'best' way is. My first thought would be that you would definitely want to be wrapping it rather than using events directly though. Whatever you do will come with some overhead, which is why we still want the normal event system.
@@agsystems8220 Just as an aside I tend to go away from events other than when it is necessary to interact with third party libraries. Instead I use System.Reactive / IObservable/ IObserver because it allows more control over subscription and disposal as well as bringing in alot of functionality (reactive.linq) also it might be more lightweight than a larger system such as mediatr (though i haven't measured it)
My first question: How on earth did you get multiple projects to show up in Rider? I can't work it out, and even the forums for Rider give the impression that they are not going to add this feature. ??
This video blog is confusing for me. Just don't mix the concepts of Event, 'scheduler' and 'service controller' (aka MediatR). MediatR has its pros and cons. Among its disadvantages is we can't see from a Controller who's running our request. In my opinion, from project to project, we have to choose the right tool. There are cases when Events are the best option, there are cases when we have to use the good old school Timer class and there are cases when it's better to split event requests and handlers and control their runtime under common Generic interface behavior via MediatR.
I don’t know why you call MediatR a “service controller”. What mediator is is very specific and it’s nothing like what you describe.. There is no scheduler here either. The interval is used for demoing the events as something that would happen in a background service, not for any scheduling purpose.
@@nickchapsas That's why I quoted those words. MediatR' requests represent any class which implements IRequest interface. MediatR' handlers represent any class which implements IRequestHandler interface. A class in CLR .Core can represent any behavior: a Data model, an Attribute, an EventArg, a DLL library, an Assembly (including late binding) even a Win Service. At some degree it's hard to put a line between App, Process, Assembly, AppDomain, Service, Context, because all these entities can represent each other. Events "operate" with methods while MediatR "operate" with classes, which is a different level of abstraction. This is an analogy to the Win OS' Service or Unix daemon model.
Like the video, but a question: In the handlers, why did you do the pattern Console.WriteLine(...); return Task.Completed... instead of await Console.Out.WriteLineAsync(...); ?
The thing I hate about events in C# is that they don't really conform to other rules of the language which restricts your ability to do simple metaprogramming and makes falling back to reflection extra confusing. I think I am even more scared of an ecosystem where there are competing strategies for handling events which will likely end up smashed together in larger projects. I think that the design of events needs to be revisited so that a backwards compatible solution can be created to make events more extensible so they can be adapted to handle more use cases.
A C# event handler is just a delegate with extra frills, allowing you to use += and -= to attach it to an even variable (like Button.Click). And a delegate is just a clunky behind the scenes class for a function pointer. Events should ALWAYS be synchronous, because they should notify you NOW about what is happening NOW. The whole example of having an asynchronous event notification is horrible.
Hi Nick, thanks for the cool video. One thing regarding MediatR that is doesn't support dynamic sub/unsub comparing to events or Rx. Everything that is registered in DI as an implementation of INotificationHandler will be called on mediator. Publish. Maybe workaround would be to override PublishCore base method.
Mediatr vs Events are drastically different in implementation and architecture pattern and arguably Mediatr is more frowned upon than events! Mediatr is about messaging at the business level, where events are about control flow at the application level
Event themselves are not obsolete. How do you represent domain side effects? Barebone events are errorprone and there weak events, observables etc to help with that.
If I can use IObservable and Rx, I try to use them every time. DryIoc has a simple built-in mediator which I added IObservable into, works great. Always thought Mediatr was a bulky library but it seems it's straightforward as well.
Message busses like RabbitMQ uses traditional events (which I agree on, it's not very elegant). Is there any way to use an implementation like Mediator for that? I see many people using traditional event handlers for Async messaging in micro service architecture.
i feel that use mediatr or events is almost the same 99% of time, i use events a lot because is do a lot of desktop apps and i think they are actually comfy to use, but still nice to see other ways to do the same.
Events are relevant. It's how the IObservable stuff works and it's how you notify other classes of state changes in any UI context. IMediator is cool if you're not doing UI work. There's also TPL.
Yeah, that's what I get for commenting on something I haven't touched for 5 years. INotifyPropertyChanged does indeed use callbacks. But the UI is still driven by events.
@@7th_CAV_Trooper I think you misunderstood me. I think that the event keyword and that event mechanism is irrelevant. Not events/callbacks or delegates as a concept. Just that specific implementation of the event feature. MAUI, Blazor etc can still use events internally but you only interact with the implementation of those events, not with the event itself.
Could someone help me? Why there is no Main() in the Program class? And also there is no reference for WebApplication.CreateBuilder(). so I couldn't run the project on my own.
@@nickchapsas So what's the alternative? I get The name 'WebApplication' does not exist in the current context. As far as I know it does not belongs to .NET Framework.
@@nickchapsas I know it is kind of old question, but I also fail making it work, for not knowing how to resolve WebApplication.CreateBuilder(). what nuget to add?
I dont think that the memory allocated here is prohibitive. If you need the most efficient version possible you can totally build something custom or use events but you have to be extremely careful because they can lead to bad performance too
while i do get the point of what you're explaining i'm not sure if one is better than the other. you compare the observer pattern with mediator the pattern 🤔
Events aren’t the observer pattern. They can be used to implement it, but at their core they are just that. Events. You can use them to implement both the observer pattern or the mediator pattern. At the end of the day, this usecase is about in process pub/sub. If you want proper observer you should use RX anyway
@@ChristophLoacker I am not deleting any comments. RUclips is notorious for deleting comments automatically that it assumes is spam. I have no control over this auto-moderation.
But why do we need events, or a library for this? On types that expose "events" just create a dictionary of Action. When the event is fired, all Actions in the dictionary are executed. To subscribe, call the public Sub(Action a) method that returns a key, and pass the key into a public Unsubscribe(Key k) method to unsub.
@iLikeCookiesQ totally agree. Much simpler, no need for yet another extra nuget lib, easier to read, etc. Not everything needs to be blown up into its own class hierarchy
Despite the fact that I was aware of the existence of the `event` keyword in C# due to my experiments in the Unity game engine, my webdev job always just creates an interface with some async handler methods, a manager that loads services implementing the interface via DI, and then executes all of the async methods before or after whatever operations it performs. Now I wonder what value there might be in refactoring such things into `event` instances and the subscriptions to them. Thoughts?
I think you have omitted biggest advantage of mediatr approach - handler does not have know anything about publisher so things are nicely decoupled. But there are completely valid use cases for events in backend applications too - for example I don't think that you would want to inject mediatr to some domain/utility class like processing progress tracker.
So you changed from events to a messagebus. When there are many publishers and many receivers you get a lot of method calls which are not filtered for their receivers. Not quite the same.
@@nickchapsas hi there. But if the use the same message, you need to filter on something (like adding an extra property) which presents something like a destination.
So...why are all the GUID's different when I do this using events (used custom delegate / EventHandler and only System.GUID as an argument instead of a System.EventArgs)? 😅 I think the objection here is purely on the pre-built System.EventArgs, not so much the whole event system (which doesn't rely on it AT ALL, it's just the default and recommended use of). The only reason this should fail is because the System.GUID instance wasn't destroyed yet; The Argument object hasn't been disposed of yet. If the effects are the issue, then the solution should be focussed on the problem... I guess what I'm saying is that if you want all your listeners to have a different GUID, just make an argument object with GUID { get { return System.Guid.NewGuid(); } }, or accept that what you put in (in Invoke) is what you'll get out (as it should)...
It's like an event aggregator. I thought everyone knew about this. I had an interview yesterday for a xamarin role and I was asked how to talk from platform to forms and my first instinct was an event aggregator. I thought that was just how IoC works. I've never used it on the backend, but I can see many use cases (like the simple example here). The problem with the GUID could be solved with: public Guid Id => Guid.NewGuid(); I still like the solution you provided though.
The Guid issue could be solved like that but it's bad practice and makes unit testing difficult. Hence just like DateTime.Now it should be put behind an interface/class and injected into other classes that need it via IoC. In the real world you might do it if you're being lazy but don't do it in an interview and be able explain why you should not do it.
@@dwhxyz to clarify, I wasn't implying that that was the ultimate solution. When we program (especially in deadlines) sometimes we need a quick solution that works. That's merely what I was suggesting. Of course it's bad to not have a piece of code testable.
Thanks for the great video. If I have a worker as a hosted service. This then fetches new orders every second as an example. This is done in a separate class where a HttpClient is needed. (Injected in the class which inhetit from BackgroundService) How does it make sense to use these mediator notifications? Are there other advantages than "only" the handling of the lifecycles? Greetings from Switzerland
Another approach could be to get an instance of the separate class via an injected ServiceProvider (core's IOC container). As a result the lifetime of the separate class (and its dependencies) is observed.
@@ryan-heath Thx for yout answer. Yes, that's right. But for me, the lifetime doesn't really matter. Should you still prefer the notification pattern? For out use case ServiceProvider often is an anti pattern.
@@maurohefti1157 for a singleton background service I don’t think service provider is an anti pattern, but in general it is an anti pattern, yes. Would I use a notification service for something that runs every few seconds? No. We have timers for that. Your service fetches for new orders. If there was a “new order arrived” event, then subscribing to such event would make more sense than pooling each few seconds for new orders.
And for those wondering, there is an Rx video coming. The approach in the end is just one example of a safe and easy alternative. Not a goto for everything event related.
I've been using Rx for a couple years now and really like it, especially for lots of async I/O calls. The big challenges are:
1) In the java ecosystem blocking threads is a basic assumption, including specifications like servlet and jdbc.
2) Its a really different way of thinking. Since everything is immutable even things like loops go away!
Kotlin, but i think most will get the gist:
Flux.interval(Duration.ofSeconds(1))
.map {
object {
val guid = UUID.randomUUID()
val time = LocalTime.now()
}
}
.doOnNext { println(it.guid) }
.filter { it.time.second % 5 == 0 }
.doOnNext { println(it.time) }
.take(10)
.subscribe()
Can’t wait for RX! After using RSJX, wanted to give it a shot in NET too
Please notify me!
Hope this one is still upcoming!
@@frotes I second this!
In Unity, event driven architecture is very useful to reduce dependencies between various components, such as UI, managers, controllers etc. It is also one way to prevent the use of Singletons.
Highly recommend implementing a message broker / mediator into a Unity project to allow communication between systems without the need to be depdendent on one another.
As someone who will be starting to use unity soon I appreciate these comments!
I am going to second Atoms for Unity and would even suggest combining it with Reactive programming using UniRx
@@Artmos I hate doing any referencing in the inspector since that will make debugging VERY HARD and annoying in bigger projects... You cannot see in a feasible way whether some function is called, asset referenced etc. That is why Atoms is a no-go but UniRx might be nice.
@@Haapavuo I think that's personal preference. I really like having my components decoupled by using ScriptableObjects. I guess if you don't like that, another solution could be a dependency injection library.
Nice try! But no way, Nick, you just replace Observer pattern with Mediator (some simple kind of), and say - Events are deprecated.
Built-in events mechanism allows to implement push and pull notification strategies, and in case of complex systems you have to mark your classes with redundant INotificationHandler + memory traffic is probably bigger.
So, there is space for discussion here, but not for loud sounds sort of "Events are deprecated". So personally for me - don't worth it.
And thanks for nice content, anyway. Keep coding.
Events, the observer pattern and the mediator pattern are all separate things
Events is a built-in observer pattern. Similar to IEnumerable (Iterator pattern, but implemented, actually better than officially described by GoF). My imho.
I agree. Events have and ever will have their place in the .Net world. They are fast, lightweight, easy to use. If one doesn't understand why an object gets captured in a lambda, then pulling a blown up nuget package and introducing tons of micro classes with dependencies to that nuget package won't help them either
@@wobuntu Agreed! Maybe I'm just bad at C# but for my front-end use cases in Unity Actions and Events do just fine.
@@jonathandunn9302 I mean he did specifically say in the video that the context of the video is backend services, not front-end work like WinForms and UIs etc.
This is another one of those .... "Don't use XXX ... it causes so many problems!!!" .... where XXX can be nulls or event etc etc. I have to say I'm struggling to remember the last time I had issues using events ... in the same way I don't think I've had problems with nulls. I know I'm becoming quite an old dog now but I'd really like to stick with my events for as long as I can. Thanks for the video.
Event in C# is very powefull but alot of pple didnt know how to use it correct.
Try to define the event as static and subscribe on constructor everytime. And you can use EventHandler instead of eventsarg object
May this video should have been named : "Benefits of using MEDIATR for events handling."
Instead you ask a question ? I'm ok to give my opinion :
With MEDIATR, it just seems that the Handlers are instanciated each time so that, their constructor param which is TransientService, will just be reinstanciated before being injected.
No magic here, this is just a MEDIATR mechanism of reinstanciating handlers here.
Thanks for showing this MEDIATR feature but for me this is absolutely not excluding the native events feature benefits.
My issue with Mediatr notifications is that the default implementation runs all the events synchronously and if one of them throws an exception the rest fail to execute. Jimmy Bogard has documentation on how to implement a different handler. It may be worth doing a video on.
You are spoiling my videos! 😂 yes the events run sequentially (not synchronously) so what you’re saying is true. There is a way around it and there is another alternative too which I’m planning to make a video on
Brighter solves this issue, I think
@@nemanjazivkovic6895 Yeah im currently using Brighter + RabbitMQ to publish and consume events out of process
@@nemanjazivkovic6895 I wanna take a look at Brighter in a dedicated video. It has really gone under me radar
Interesting..
Pretty much an almost flawless approach to replacing events in modern apps. But I wanted to see what could be a flaw with this approach. The only thing I can think of that this doesn't do in a simple way is unsubscribing from the notification. Since MediatR uses DI to find the handlers, they are automatically subscribed by class signature.
A way to remedy this I think is to create a optional method on a new INotificationHandler: Task ShouldSubscribeAsync();
This method is automatically called upon registration or lazily during runtime, and based on the result, either keeps or deregisters that notification handler instance for that scoped resolution of that request. Singleton would invoke this method once, transient for every request, etc.
Otherwise, I feel like you have to manually deregister the dependency based on the result of the method in the early stages of the application which shouldn't have this type of logic if you are going for a clean architecture and separation of concerns. What do you guys think?
It looks like there is no "dynamic" way of subscribe/unsubscribe 🤔
There's really no way to get around events when programming for games, where there are so many individual systems running (for instance AI/NPC) as well as player input and possibly multiplayer/server input. Also when working with speech recognizers, the recognizer isn't predictable if the speech is continuous, so events will be necessary to collect the results as they trickle in.
One could set up ones own polling mechanisms but they tend to be a lot less sophisticated when created from within something like C# (i.e. no interop) than the stuff perfected by framework library creators over the course of many years. The top layer of event design should be handled by you of course, but under the hood there can be a lot of elaborate stuff going on to make events less expensive and just slicker, like hooking up to system interrupts or sniffing other events to start the polling, or up its frequency, only when logically necessary.
Events are a crucial part in several domains, Component based programming for example. Here is demonstrated that in a specific domain (Web handlers) they are better alternatives. Event here it is still debatable, since handlers are created and disposed for every notification. You may want this in some case, but perhaps you don't in some others
That blur at the start 😂 I’m curious
Video used to have a sponsor and the write line was saying “Thanks ”, but I decided to not go with them so I blurred it. That’s why my website call-out is from another video too
Makes sense, I was thinking "What kind of insidious nonsense are we writing to the console?"
I have been enjoying Observable for a while, between Reactive Extentions, Reative UI, etc.
I also enjoy F#.
From what I recall, in F# events can be subscribed to as observables.
I expected him to talk about observables are they are actually that are evening used to replace events. Mediatr isn’t really comptable at all. It’s just a hidden factor Service calling back into the ioc container on each invocation… that’s easy to do on your of if that’s what you want but it has nothing to do with the events.
@@mwwhited I think I agree with you.
But also might be whether or not we are talking about "Events" or "events" (IYKWIM).
My preference for "events" at the moment is MassTransit.
I think an "event sourcing system"* that works by registering a series of Observable Subscriptions (or even just Observable pipelines, because then you can return something, which could be handled like a Task await on the "Other End" would be very cool).
* Referring to Mediatr and MassTransit, this probably has an actual name, but I don't know it :P.
It can also be done in C# Observable.FromEventPattern used it a few times.
This was finally the mediator video that clicked for me
Really important to note here: we're talking about a captured lambda or function, not about a capturing lambda or function. Big difference. The event is capturing its handler functions, which if they capture any transient service objects, they both remain cached.
Just for the sake of info completion, what is capturing a lambda or function would be like then?
@@mohamedeffat54 I guess he is talking about returning a delegate
C# events are a language feature to support the observer design pattern. If a task at hand isn't solved by that, then don't use it.
or the mediator pattern. I love that one
I agree with the sentiment expressed a lot here, in the sense that I don't think you sufficiently expressed why events should be deprecated. Your original architecture is flawed, and replacing one publisher-subscribed mechanism for another observer pattern really doesn't make that much of a difference, except for the handlers apparently being newed-up on every invocation with MediatR (which I believe will be a significant expanse of your architecture design). If you truly want to get rid of events as much as possible, you should switch to Reactive Extensions, which is a proper way to handle data streams.
I could definitely have used a better original example. I will revisit that topic when I make my observers video
When you are writing "Hello World", you do not really need events. You can use a mediator or not. Once you start writing something meaningful, you use something like BackgroundWorker or SerialPort or other dotnet APIs, which fire events. Once you go beyond junior level, you start working on larger projects and work with third party libraries written in other languages with COM interfaces, or do tricky stuff with operating system components. They fire C# events.
I work in larger distributed systems and MediaR is just fine for decoupling certain aspects of your business layer. No need for other 3rd party libraries or COM interfaces when a simple pub/sub model is needed.
This is a clever alternative but what is the performance difference for expensive event handlers. It seems that Mediator would create and destroy the objects for every call.
But that’s fine because you want proper scoping. The risk of closure in the event handler approach is way more dangerous because it won’t be just slow it will also capture dependencies and cause bugs
People are often worried about DI having to have to create many objects and that being slow or taking too much memory. In reality, if you for example have a C# class with some logic and say 4 dependencies (some injected services), the resulting piece of memory allocated for that object is really just 4 pointers to the dependencies.
Now compare that to a foreach that creates an iterator and causes about the same. But somehow people don't think about that.
@ If it's transient then it's constantly reallocating those 4 dependencies, if it's an iterator then it's just allocated once.
@@ShadoFXPerino yes but the point I am trying to make is that people are not rational in this regard and somehow fear this one allocation of the transient object. The same people then go on and create a monster Linq in some hot spot method of some Singleton.
In my opinion it is a good price to pay for having the scoping clearly handled.
@ You are very correct on that irrational obsession, and I'll admit, I have probably obsessed just like that on more than one occasion. However, I think the impact this could have on the garbage collector when you subscribe with many handlers can be a valid concern. Of course, then your main problem is just that you think you have too many handlers, but if you subscribe with stateless objects, like most services, then you can argue that this is waste... Though I wonder, if there is an "INotificationHandler" interface, then maybe there also exists something like an "INotificationStateless" interface from which objects would be put in a singleton.
Thank you for great video as always.
16:18 : I expect to have the same Guid over and over because Trainsient services follow the lifetime of its injector. Since TickerService is Singleton and even not its injector (BackgroundService) is a singleton, TransientService injected into TickerService will not be disposed until TickerService is disposed. And whenever the event methods are called it will use same TransientService. And the same instance of TransientService will have the same guid which is assigned once.
I personally do not see a problem with event system here. I agree that MediatR is a modern approach and very flexible. However this is a bit missleading.
The only way this would work without passing the factory of the service down would be to create a new class every time. It’s bad and I actually do events a service of not showing how bad it can really get. The feature itself isn’t bad obviously, but people (and I invite you to check on GitHub) get it more wrong than right
I completly agree, if TickerService would want to new instance on every call, It would need to have a somewhat factory for TransientService, not an instance itself.
Factory is definitely a shortcoming in the worker services. I have an inmplementation on stackexchange because its definitely needed.
Can't you just workaround this by resolving the service every time with the IServiceProvider interface instead of injecting it into the singleton?. Nice video as always btw
@@yunietpiloto4425 yes but that is seen as the servicelocator anti-pattern
You didn't mention that `event` can be used with any delegate type. I usually just do `event Action`. I don't find the object sender to be of much use outside of specific UI frameworks.
I have a video about Func and Action coming and I mention it there
Microsoft guidelines recommends using EventHandler for events. Also the reference to the sender is quite useful during debugging if your subscriber handles messages from couple producers.
11:09 This feels a lot like a pretty common DI issue and it's usually solved with factories. Autofac will resolve Func to a factory for transient service to allow you to do what you're talking about. Getting the ID would then look like _transientServiceFactory().Id which would create a new instance on each tick as desired.
Hey Nick, I'm a bit confused about the GUID issue. If you're requesting transient services from the BackgroundService shouldn't you inject the ServiceProvider and then get a new scope and resolve services every tick? Wouldn't that give a new GUID?
Injecting the ServiceProvider is an anti pattern called service locator. It should be avoided because you never know what services will be resolved if you do that
@@nickchapsas MediatR is really just a wrapper around a service locator. If you are using Microsoft DI it is the service provider that it is calling in the end is it not?
@@RENAUDADAM service locator pattern is an anti pattern which should be avoided in most use cases, but if you are building frameworks (such as mediator) then it can be okay, but using it as a normal way of pulling "magic" dependencies out of thin air into a class should be avoided, it makes your code hard to test. It goes against the dependency inversion principal.
@@RENAUDADAM sure but it’s not MY service locator. I don’t know about any of it and nothing in my application knows about it either. There is a big difference there. Dictionary.ContainsKey uses gotos. That doesn’t mean that I would use gotos
@@nickchapsas great video man! I have a question, sorry i don't have much experience. If i want a new viewmodel for example so it has to be "empty" or as its initial state, how do i get one without saying new() or the service provider? For example the user switches between some views and everytime they have to be resetted..
Reactive Extensions offer better alternative, it even offer ability to transfom normal events to IObservable
They do but I wanna make a dedicated video on them so I had to not mention it
@@nickchapsas really looking forward to Rx video!
I wonder what the performance difference is between mediatr and manually getting the transient service from the DI in the event
🍎 and 🍊. Not deprecated at all. What about file system, network or other devices? I has to be a callback or event.
Not at all. You can hook up whatever you want in there, they don’t have to be events. Also a callback and an event are 🍎 and 🍊
@@nickchapsas My point was that events should not be used in the same circumstances as mediator notifications, but events and callbacks can. If I were to create something like the FileSystemWatcher, using mediator would be a bizarre implementation. Also, it would be fun if libraries started to implement events as mediator notifications and disagreed on what version or library to use.
@@EspenSkaufel Ofc they are not the same, I never said they are, but the Notifications implementation of MediatR can give you an argueably better alternative for this usecase. Ofc you would not use MediatR for the usecase you mentioned. An observer pattern would be way better here. Events can be used to implement callbacks. Notifications can be used to implement events. Events as a concept is the root, not the end. Event he callbacks you mention aren't events. They are just callbacks triggers by something. That something can be events but it can be something else too.
@@nickchapsas Sorry for being annoying, bad habit. Your title triggered the response, as I expect to see developers trying to avoid using events at all costs after watching this. Knowing when to use what is why experience matters in software development. Just like with inheritance, it is bad most times, good sometimes 🥴.
Good timing. I happen to be dealing with this exact thing right now. Thanks!
Sorry, not convinced at all.
Your expected result which I would sum up as:
1. Handler of event without "memory", new instance every time.
2. async calling.
It's not "default" setting for events, but still it's very easy to make them work that way. With simpler code in which you see the behavior. If I see code, which looks like some plain old class with injected dependensy to some service, and for some strange reason this class is instanced every time, I woud not call this code good.
You could get the same result with just simple factory or get returning new instance change. Like one line of code and you know -> Ok, I will get new guid every time I use it.
As for the async you have full control with events over how and when event would fire. You can filter subs, you can fire them sync, you can use tasks, queues and bilion other things with that. async handler isn't always a way do it.
To sum up, question.
Let change your example. I want it to write those guids on some file -> poor man simplest log.
You are a fantastic teacher, I'm glad I found your videos.
Danke!
Events are not the most intuitive things to create. One thing I've sometimes used them for is cross thread communication, but in doing so you may also need to marshal to the other thread, since normally the thread that fires the event, also does the listener work.
forgetting to unsubscribe from events can also be a source of memory leaks.
It can't get anymore simple than this. Thank you soo much howtobasic!
I dont often comment on youtube. But dang as a senior engineer working for microsoft. This stuff is really good .
Implementing async events really isn’t that much work, you can just use delegates and task with event handlers and it ends up working quite nicely, I’m surprised there isn’t for support/documentation on async events as in certain use case there very powerful
0:15 great transition, at first I didn't even notice it.
just to make sure. Does this mean that a new instance of every eventhandler (class that inherits from INotificationHandler) is created each time that event of type T happens?
Depends on how you register mediatr
I wrote something, inspired by Aurelia, called EventAggregator that is this same thing. It has been easy to test functionality that only happens when an event is published too. It's been tough since the team I'm currently working with is stuck on events but are slowly starting to see how easy event aggregation is to use in comparison to wiring events all over the place. Plus...you can have two things working together without needing to know of each other's existence. Both components have a dependency on IEventAggregator that ties them together. Just like with anything event related...have to make sure you clean up after yourself and unsubscribe from events when they aren't needed any longer. I'm a big fan of this approach to domain events.
One thing Visual Studio has over Rider is that to looks better in video regardless of the theme selected.
Object modularity vs dependency injection. If you'd have went back to Y2K and told them you're going to reinstantiate every object for every tick they'd call you a nutjob. Then we had global internet, gigs of ram, stagnating CPU clock rates, and 32-core CPUs and it didn't sound so stupid anymore.
You still have micro services though
11:59 Unrelated, but I was curious about why I often see types being passed into methods to mark an Assembly for scanning? Why not pass in the actual Assembly object, possibly obtained from Assembly.GetExecutingAssembly() ?
Or is is purely for consistency, if the Assembly you want to refer to is not the current executing assembly, so instead you pass in a type from the aseembly you intended to target?
It’s for deterministic execution. Code can be moved around, the project might be referenced by another project etc
So at 15:00 where you're passing in the instance of the transient service via DI... does this mean MediatR is constructing/allocating a new instance of EverySecondHandler each time that event is fired?
It depends on the lifetime of the handler. The default is transient yes, but you can change it.
Very cool! This gives me some ideas for useful background services
Amazing video as always. Just to clarify, Events/Observer and the Mediator pattern solve two different problems. In the former, you are interested in WHAT happened as well as WHO emitted that event. In the later, you are interested in WHAT happened but not always WHO emitted that event. The coupling is also different, in the Event/observer pattern, the subscriber should know the existence of the publisher, whereas in the Mediator pattern, the publisher doesn't know the existence of the subscriber and the subscriber doesn't know the existence of the publisher. Event/Observer are ideal for things like GUI or specialized services, whereas mediator is well suited for application wide communication.
You shouldn't be mixing events and observer. They are different things. Events can be used to implement the observer pattern but the observer pattern doesn't need events to be implemented.
@@nickchapsas Of course. I was just implying that c# events are just syntactic sugar for the ol' gang of four observer pattern.
An IDisposable object that exposes events should always assign null to the events on disposal to prevent memory leaks. UI programming would be very difficult without events.
This is just an EventAggregator, which have existed for a long time. If you're writing WPF apps, then this stuff is no brainer though I still prefer events because it is much cleaner and I will always know the source of the event.
How do I run this Api in Visual Studio 2022 ver 17.8.6 and see a Console output? Using minimal APi with no swagger, auth or https. Only options i see is http, IIS Express and WSL...
maybe in set models for apps, where you can somewhat predict what component will be connected to another. But in Unity it's a lifesaver.
When you’re using the built in events. The handler is listening for events from a specific instance. How would you accomplish the same thing using mediatr eventhandlers? For example if you have two instances of TickerBackgroundService running but you only want events from one of them?
I love that you're covering this.
You can also do something similar with reactive extensions
I use IServiceScopeFactory when I need to consume transient or scoped in a singleton
I got an application in blazor build around events.
Events only make sense around state.
Since backend is 90% statelless then you may never need events.
Did you ever use ReactiveExtensions an if so, do you have an opinion on it?
Looks like something from Java to me. You have an observer/listener pattern with a mediator. I think it's good for application or system wide events as it only adds dependencies to the mediator. But for local messages C# events are better. A lot less code and slightly better performance.
You’re mixing observer and mediator. They are completely different things. There will be an observer video coming soon
@@nickchapsas Notification listeners are observers in your example.
@@CockroachSlidy No they are not. They aren't observing anything. They are notification handlers but they don't listen to anything.
I do like this approach better because there are other memory allocation issues if you don't set things up properly with your event subscriptions and unsubscriptions in a more traditional publisher/subscriber model.
Hello, i just don't get it, who instantiating EverySecondHandler and EveryFiveSecondHandler? They just defined in cs file and no instantiation happened
The dependency injection framework is handling the initialisation
You Go FAST But You're Great!
This video completely dropped the ball. Madiatr not only mixes command and query with notifications, it also is a terrible implementation of command snd query since it unifies both into one irequest interface.
Not only could you implement it better yourself in 5 minutes since command and query basically consists of just a handful of interfaces, videos like this, claiming this is somehow more modern than c# events are exactly the reason I've seen code bases overengineered and wannabe architects using mediatr for all application communication when 90% of it is synchronous.
DONT implement solutions before you run into a problem. I HATE this "I found a new library, now I'll use it everywhere and claim this is the state of the art way of doing things, feeling smart".
I like your videos but please be aware that videos like this are regularly used by shitty developers to make the project hell for their colleagues.
Libraries are tools. They should be used where appropriate. Vlaiminb things like "this is how it's done nowadays" is massively damaging.
Sry, for this maybe "stupid" question, but if you attach the eventHandler in the constructor then how you detach the eventHandler, if the object is destroyed? Do you have to overwrite the destruct constructor (~TickerService)? Or what will be best solution?
no need, since when tickerservice is collected also its methods are collected. you do need to be wary of events and eventhandlers though, in other cases you could cause a memory leak
@@TheToeb Memory leak is what i thought. So the gc will take care of this case...thanks!
Not really a stupid question at all, and hits at the root of the problem. The difference between the two models is who 'owns' what. In the older event model the event handler is responsible for doing the work. The event pulls in the objects it needs, and then does the work. The object itself has no idea what might happen to it, which can be a problem if that object might want to do something that those closures need to know about (such as being disposed of, or switched out). In the publishing model data is pushed to objects, and the event has no idea what might be done with that data. The major difference is that the object definitely knows about event handler, and so can definitely send messages back to it. 2 way communication is possible, and basic functionality can be available by default (such as dependency injection, or disposal).
Unfortunately there is no general answer to what an event closure should do in the case of disposal of one of it's dependencies, but defaulting to disposing itself (and informing it's other dependencies it has done so) seems reasonable. It is inherently a 2 way communication problem. Standard events are a lightweight solution where we know that one way communication is sufficient, but for anything above the lowest levels it usually isn't. How you extend it to a 2 way system is a more complicated problem, and I'm not qualified to post an opinion on what the 'best' way is. My first thought would be that you would definitely want to be wrapping it rather than using events directly though. Whatever you do will come with some overhead, which is why we still want the normal event system.
@@agsystems8220 Just as an aside I tend to go away from events other than when it is necessary to interact with third party libraries. Instead I use System.Reactive / IObservable/ IObserver because it allows more control over subscription and disposal as well as bringing in alot of functionality (reactive.linq) also it might be more lightweight than a larger system such as mediatr (though i haven't measured it)
My first question: How on earth did you get multiple projects to show up in Rider? I can't work it out, and even the forums for Rider give the impression that they are not going to add this feature. ??
Me finally getting a hang with events.
Nick: nah not relevant..
Gotta watch this
This video blog is confusing for me. Just don't mix the concepts of Event, 'scheduler' and 'service controller' (aka MediatR). MediatR has its pros and cons. Among its disadvantages is we can't see from a Controller who's running our request. In my opinion, from project to project, we have to choose the right tool. There are cases when Events are the best option, there are cases when we have to use the good old school Timer class and there are cases when it's better to split event requests and handlers and control their runtime under common Generic interface behavior via MediatR.
I don’t know why you call MediatR a “service controller”. What mediator is is very specific and it’s nothing like what you describe.. There is no scheduler here either. The interval is used for demoing the events as something that would happen in a background service, not for any scheduling purpose.
@@nickchapsas That's why I quoted those words. MediatR' requests represent any class which implements IRequest interface. MediatR' handlers represent any class which implements IRequestHandler interface. A class in CLR .Core can represent any behavior: a Data model, an Attribute, an EventArg, a DLL library, an Assembly (including late binding) even a Win Service. At some degree it's hard to put a line between App, Process, Assembly, AppDomain, Service, Context, because all these entities can represent each other. Events "operate" with methods while MediatR "operate" with classes, which is a different level of abstraction. This is an analogy to the Win OS' Service or Unix daemon model.
Like the video, but a question: In the handlers, why did you do the pattern Console.WriteLine(...); return Task.Completed... instead of await Console.Out.WriteLineAsync(...); ?
The thing I hate about events in C# is that they don't really conform to other rules of the language which restricts your ability to do simple metaprogramming and makes falling back to reflection extra confusing. I think I am even more scared of an ecosystem where there are competing strategies for handling events which will likely end up smashed together in larger projects. I think that the design of events needs to be revisited so that a backwards compatible solution can be created to make events more extensible so they can be adapted to handle more use cases.
A C# event handler is just a delegate with extra frills, allowing you to use += and -= to attach it to an even variable (like Button.Click). And a delegate is just a clunky behind the scenes class for a function pointer.
Events should ALWAYS be synchronous, because they should notify you NOW about what is happening NOW. The whole example of having an asynchronous event notification is horrible.
I use events for a server side blazor session manager. It raises events to force users to log out on session expiry
Hi Nick, thanks for the cool video.
One thing regarding MediatR that is doesn't support dynamic sub/unsub comparing to events or Rx.
Everything that is registered in DI as an implementation of INotificationHandler will be called on mediator. Publish.
Maybe workaround would be to override PublishCore base method.
thanks master, but we can use new guid before publish? its same right? and use transient services
Hi, Nick! At 4:47 i see autocorrection "handELR" -> "handLER". What plagin You use for that?
Video editing 😂
The dance while pressing buttons killed me ahaha
Mediatr vs Events are drastically different in implementation and architecture pattern and arguably Mediatr is more frowned upon than events!
Mediatr is about messaging at the business level, where events are about control flow at the application level
There is nothing business specific for MediatR. It was not made for that and it was not build around that idea.
I wouldn't say its dead node js is progressing a alot on events, also if you don want to use packages you could use the observer pattern.
Absolutely. This video isn’t about the concept of events but about the event keyword and mechanism
Now, that I finally wrapped my head around events and event handling, it's outdated. I'm too old for this...
What about performance? Does MediatR delivery the same performance as old fashioned events?
Event themselves are not obsolete. How do you represent domain side effects? Barebone events are errorprone and there weak events, observables etc to help with that.
Sure but I refer to barebone events, not other implementations of the concept
How to unsubscribe one "Mediator Event Handler" ?
What do you think about Channel?
Channel is cool and I’ll be making a dedicated video on it
Interesting, because I am now using it a lot with Blazor.
In this case would be similar to have Masstransit in place instead of MediaR, I will have more benefits (persistence, queuing) what is your opinion?
Sometimes you don't need persistence and/or queuing. You just want to decouple some action from running in the same namespace for example.
Shoutout for Reactive Extensions ✌
That’s something that I’ll be taking a look at very soon btw
If I can use IObservable and Rx, I try to use them every time. DryIoc has a simple built-in mediator which I added IObservable into, works great. Always thought Mediatr was a bulky library but it seems it's straightforward as well.
Message busses like RabbitMQ uses traditional events (which I agree on, it's not very elegant). Is there any way to use an implementation like Mediator for that?
I see many people using traditional event handlers for Async messaging in micro service architecture.
Maybe building a wrapper for each event? Of course you still need to subscribe to an event, but you wouldn't have the scoping problem.
i feel that use mediatr or events is almost the same 99% of time, i use events a lot because is do a lot of desktop apps and i think they are actually comfy to use, but still nice to see other ways to do the same.
I am so glad I subbed to you. This is epic!
Events are relevant. It's how the IObservable stuff works and it's how you notify other classes of state changes in any UI context.
IMediator is cool if you're not doing UI work. There's also TPL.
Observable works with callbacks not events
Yeah, that's what I get for commenting on something I haven't touched for 5 years. INotifyPropertyChanged does indeed use callbacks. But the UI is still driven by events.
@@nickchapsas Do you think IMediator replaces TPL?
@@7th_CAV_Trooper I think you misunderstood me. I think that the event keyword and that event mechanism is irrelevant. Not events/callbacks or delegates as a concept. Just that specific implementation of the event feature. MAUI, Blazor etc can still use events internally but you only interact with the implementation of those events, not with the event itself.
@@nickchapsas yeah, I'm with you now. btw, love your channel and share your videos often.
Could someone help me? Why there is no Main() in the Program class? And also there is no reference for WebApplication.CreateBuilder(). so I couldn't run the project on my own.
You don't need Main anymore. It is implicit. Same with the common using statements. They are added behind the scenes by default.
@@nickchapsas So what's the alternative? I get The name 'WebApplication' does not exist in the current context. As far as I know it does not belongs to .NET Framework.
@@nickchapsas I know it is kind of old question, but I also fail making it work, for not knowing how to resolve WebApplication.CreateBuilder(). what nuget to add?
But Nick one of your video you said MediatoR will take more memory and will it be fit for every time, like a silver bullet?
I dont think that the memory allocated here is prohibitive. If you need the most efficient version possible you can totally build something custom or use events but you have to be extremely careful because they can lead to bad performance too
while i do get the point of what you're explaining i'm not sure if one is better than the other. you compare the observer pattern with mediator the pattern 🤔
Events aren’t the observer pattern. They can be used to implement it, but at their core they are just that. Events. You can use them to implement both the observer pattern or the mediator pattern. At the end of the day, this usecase is about in process pub/sub. If you want proper observer you should use RX anyway
@@nickchapsas Sad to see you keep deleting my comments pointing out that your not 100% right. Made you lose a day-1-fan
@@ChristophLoacker I am not deleting any comments. RUclips is notorious for deleting comments automatically that it assumes is spam. I have no control over this auto-moderation.
1:47 no eventhandler don't need to be nullable, you are already checking for null with ?.
I am using nullable reference types so yeah it should be nullable
Man, Nick great video again.
But why do we need events, or a library for this? On types that expose "events" just create a dictionary of Action. When the event is fired, all Actions in the dictionary are executed. To subscribe, call the public Sub(Action a) method that returns a key, and pass the key into a public Unsubscribe(Key k) method to unsub.
Yeah you can totally do that. I wanted to show us safer way that you can’t get wrong
@iLikeCookiesQ totally agree. Much simpler, no need for yet another extra nuget lib, easier to read, etc. Not everything needs to be blown up into its own class hierarchy
Despite the fact that I was aware of the existence of the `event` keyword in C# due to my experiments in the Unity game engine, my webdev job always just creates an interface with some async handler methods, a manager that loads services implementing the interface via DI, and then executes all of the async methods before or after whatever operations it performs. Now I wonder what value there might be in refactoring such things into `event` instances and the subscriptions to them. Thoughts?
Hey Nick can you publish video of mostly used design patterns in c# and how ? And when to used it.
I think you have omitted biggest advantage of mediatr approach - handler does not have know anything about publisher so things are nicely decoupled. But there are completely valid use cases for events in backend applications too - for example I don't think that you would want to inject mediatr to some domain/utility class like processing progress tracker.
Nick Why not replace C# event with Reactive Extensions? Need to know your opinion about it
Interesting extension. Did not know so far
So you changed from events to a messagebus. When there are many publishers and many receivers you get a lot of method calls which are not filtered for their receivers. Not quite the same.
Sure I do. The check is done on the type of the Notification.
@@nickchapsas hi there. But if the use the same message, you need to filter on something (like adding an extra property) which presents something like a destination.
@@limbique No you don't
@@nickchapsas In that case it isn't a "replacement" for events. (don't get me wrong.. I love your content
Nick you such a legend bro, I learn so much from you, keep it up!
So...why are all the GUID's different when I do this using events (used custom delegate / EventHandler and only System.GUID as an argument instead of a System.EventArgs)? 😅 I think the objection here is purely on the pre-built System.EventArgs, not so much the whole event system (which doesn't rely on it AT ALL, it's just the default and recommended use of). The only reason this should fail is because the System.GUID instance wasn't destroyed yet; The Argument object hasn't been disposed of yet. If the effects are the issue, then the solution should be focussed on the problem... I guess what I'm saying is that if you want all your listeners to have a different GUID, just make an argument object with GUID { get { return System.Guid.NewGuid(); } }, or accept that what you put in (in Invoke) is what you'll get out (as it should)...
It's like an event aggregator. I thought everyone knew about this. I had an interview yesterday for a xamarin role and I was asked how to talk from platform to forms and my first instinct was an event aggregator. I thought that was just how IoC works. I've never used it on the backend, but I can see many use cases (like the simple example here).
The problem with the GUID could be solved with:
public Guid Id => Guid.NewGuid();
I still like the solution you provided though.
The Guid issue could be solved like that but it's bad practice and makes unit testing difficult. Hence just like DateTime.Now it should be put behind an interface/class and injected into other classes that need it via IoC. In the real world you might do it if you're being lazy but don't do it in an interview and be able explain why you should not do it.
@@dwhxyz to clarify, I wasn't implying that that was the ultimate solution. When we program (especially in deadlines) sometimes we need a quick solution that works. That's merely what I was suggesting. Of course it's bad to not have a piece of code testable.
It's not dead; it's just not a best practice in dependency injection :)
Thanks for the great video. If I have a worker as a hosted service. This then fetches new orders every second as an example. This is done in a separate class where a HttpClient is needed. (Injected in the class which inhetit from BackgroundService) How does it make sense to use these mediator notifications? Are there other advantages than "only" the handling of the lifecycles? Greetings from Switzerland
Another approach could be to get an instance of the separate class via an injected ServiceProvider (core's IOC container). As a result the lifetime of the separate class (and its dependencies) is observed.
@@ryan-heath Thx for yout answer. Yes, that's right. But for me, the lifetime doesn't really matter. Should you still prefer the notification pattern? For out use case ServiceProvider often is an anti pattern.
@@maurohefti1157 for a singleton background service I don’t think service provider is an anti pattern, but in general it is an anti pattern, yes.
Would I use a notification service for something that runs every few seconds? No. We have timers for that.
Your service fetches for new orders. If there was a “new order arrived” event, then subscribing to such event would make more sense than pooling each few seconds for new orders.
This is a really good content. Thank you.