When should I use an event handler over an event aggregator? - c#

When should I be using an Event Handler versus an Event Aggregator?
In my code, I have two ViewModels that controlled by a parent ViewModel, I am trying to decide if I should just use an event handler to talk between them? Or use an Event Aggregator? It is going to just be simple method call, I don't require parameters to be passed between them.

The way I see it, the EventAggregator is usually the heavy gun used when you want to publish an event to the entire application and more specifically - when you don't know who exactly is listening.
In your scenario that's not really the case, you have 2 view models that want to communicate, but they both know each other. So there is no real reason you can't use events.
I'll just mention that if you want to keep it a little more loosely-coupled - make an interface for each of the viewmodels that exposes the event. This way each VM will use the other VM's Interface instead of a specific instance.

Here is a link with some good info (that is alive as of 5/2019)...
https://learn.microsoft.com/en-us/previous-versions/windows/apps/xx130639(v%3dwin.10) (Microsoft, Prism)
The "Making key decisions" section describes when to use it.
Events in .NET implement the publish-subscribe pattern. The publisher and subscriber lifetimes are coupled by object references to each other, and the subscriber type must have a reference to the publisher type.
Event aggregation is a design pattern that enables communication between classes that are inconvenient to link by object and type references. This mechanism allows publishers and subscribers to communicate without having a reference to each other. Therefore, .NET events should be used for communication between components that already have object reference relationships (such as a control and the page that contains it), with event aggregation being used for communication between loosely coupled components (such as two separate page view models in an app). For more info see Event aggregation.
I crudely see this as suggesting C# events are good for layers (UI listening to bus logic) or parent/child (an instrument listening to its contained devices) and event aggregation is good for siblings (e.g., sibling UI panels or device to device communication).

Related

Using Events Delegates in multi tenant web application

I'm developing a multi tenant n-tier web application using asp.net Mvc 5.
In my service layer I am defining custom events for every important action and raising these events once these actions are executed. For example
Public event EventHandler EntityCreated;
Public void Create(Entity item) {
Save(item);
......
EntityCreated(this, item);
}
I intend on hooking up business rules and notifications to these events. The main reason I want to use events is decoupling of the logic and easy plug-ability of more events handlers without modifying my service layer.
Question:
Does it make sense using events and delegates in asp.net?
Most examples I find online are for win forms or wpf. I get the advantage when it comes to multithreaded applications. Also the events are defined once per form and are active for the lifetime of the form.
But in my case the events will be per http request. So is it an overhead defining these events?
As others pointed out that pub/sub or event bus is one solution. Another solution is something like what you are trying to do here but make it more formal.
Let's take a specific example of creating a customer. You want to send a welcome email when a new customer is created in the application. The domain should only be concerned with creating the customer and saving it in the db and not all the other details such as sending emails. So you add a CustomerCreated event. These types of events are called Domain Event as opposed to user interface events such as button click etc.
When the CustomerCreated event is raised, it should be handled somewhere in the code so that it can do the needful. You can use an EventHandlerService as you mentioned (but this can soon becomes concerned with too many events) or use the pattern that Udi Dahan talks about. I have successfully used Udi's method with many DI Containers and the beauty of the pattern is that your classes remain SRP compliant. You just have to implement a particular interface and registration code at the application bootstrap time using reflection.
If you need further help with this topic, let me know and I can share with you the code snippets to make it work.
I have implemented Udi Dahan's implementation as pointed out by #Imran but with a few changes.
My Events are being raised in a Service Layer and for that using a Static Class dint seem right. Also have added support for async/await.
Also going down the Events & Delegates path did work out but it just felt like an overhead to register the events per request.
I have blogged my solution here http://www.teknorix.com/event-driven-programming-in-asp-net

Should EventAggregator be used for point to point or broadcast messaging

I am using the EventAggregator in Caliburn.Micro in a Windows Phone 8 App.
There are a number of places where the view-models implement IHandle<SomeClass>.
My Question is since multiple classes will be handling when an object of SomeClass is published, even though they may not be the intended recipient. So what is the best way to deal with this....
Design message classes with different names (but essentially the same content) so that all communication between view-models is strictly point-to-point ?
Or put a source property in message classes so that all receivers know the source of the message so that it can be conditionally processed ?
There is no right or wrong answer to this question. As I see it:
There are cases when you want point-to-point and it is okay to have a specific message type (class) for solely this purpose
There are cases when you want an event like (broadcast) behavior
You can also have broadcast with active cancellation just like the one you have in System.Threading.Task, or like the one in the WPF eventing model where each handler is a visitor and can set the Handled flag of an event argument (say SomeClass) to true so that the other handler know they shouldn't be processing it anymore.
Also the name EventAggregator typically points to the fact that it's most common use is to aggregate handlers i.e. do broadcasting (at least this is how I see it)
Think about the WPF eventing model as an analogy.. You raise the event (publish it) but don't really care about how many handlers you have or what they are doing.

Best pattern for change notification (events or delegates)

I have a solution where i pass a collection of items from a source to a presenter. When the source is updated I want to be able to notify the presenter to show the new result.
What comes to mind is to make a ChangeNotification class, pass it along with the result and have that class notify the presenter. Now as I see it this can be implemented in two ways, either ChangeNotification can have events that the presenter subscribes to, or it can have delegates that the presenter sets and the source calls if it is not null.
The benefits of using events is that more than consumer can react to the notification and you can hook up reactive extensions to it, the downside is that you have to manage subscribe/desubscribtion of the events for proper garbage collection. Delegates are simple but you lose some flexibility.
What is the most elegant pattern for situation like this? Is there some other way I haven't thought of?
If you will have multiple observers, Events or MultipleDelegates would be required. If you will only have one observer, and want to enforce that, a delegate would suffice. However, in terms of which is best, IMHO I would say the event is more flexible and lends itself very well to the pattern. The ObservableCollection and INotifyPropertyChanged are event based implementations. By the way, +1 to tbischel for the references to these classes.
There are two built in patterns for this scenerio.
First, you could implement the INotifyPropertyChanged interface. This is better if you want to notify the presenter of changes to properties of the objects themselves in the collection. (or the source object itself, if that is where changes occur).
The second is to pass your presenter an ObservableCollection containing your objects. This is better if you want to notify the presenter that an item has been added or removed from the collection. Both are event driven models that any subscriber could hook into.
Edit: The underlying pattern is the "Observer" pattern... you can roll out your own version if you want, you have the details down.
I agree with the other answers that INotifyPropertyChanged, INotifyCollectionChanged and other related interfaces are property the first place to turn but I wanted to add in third option which would be to implement the observer pattern. If your are not familiar with this pattern, it is how Java achieves it's event functionality through what are called event listeners. There is no reason why this pattern cannot be adopted in C# though and in some cases it may provide a more elegant solution than the use of events and delegate especially when there may be several coordinated events that are generally all subscribed to by an interested party.
Another option too is deriving from DependencyObject and implementing DependencyProperties in order to get the change notifications that are built-in and that are optimized for WPF. I tend not to go this route because I don't like the requirement of having a specific base class but there are some good arguments for why it is sometimes the right choice and in fact some MVVM frameworks even use it as the basis of change notifications for ViewModel classes too.

CompositeWPF: EventAggregator - when to use?

I've been looking in to the Composite Application Library, and it's great, but I'm having trouble deciding when to use the EventAggregator... or rather - when NOT to use it.
Looking at the StockTraderRI example, I'm even more confused. They are using the EventAggregator in some cases, and "classic" events in other cases (in for example the IAccountPositionService interface).
I've already decided to use it for communication with a heavy work task, that should run on a background thread. In this case the EventAggregator offers marshalling of threads behind the scenes, so I don't have to worry much about that. Besides that I like the decoupling this approach offers.
So my question is: When I've started using the EventAggregator in my application, why not use it for all custom events?
This is a good question. In Composite WPF (Prism) there are 3 possible ways to communicate between parts of your app. One way is to use Commanding, which is used only to pass UI-triggered actions down the road to the actual code implementing that action. Another way is to use Shared Services, where multiple parts hold a reference to the same Service (Singleton) and they handle various events on that service in the classical way. For disconnected and asynchronous communication, as you already stated, the best way is to use the Event Aggregator (which follows closely Martin Fowler's pattern).
Now, when to and not to use it:
Use it when you need to communicate between modules. (for example, a Task module needs to be notified when a Task is created by any other module).
Use it when you have multiple possible receivers or sources of the same event. For example, you have a list of objects and you want to refresh it whenever an object of that type is saved or created. Instead of holding references to all open edit/create screens, you just subscribe to this specific event.
Don't use it when you only have to subscribe to normal events in the Model View Presenter area. For example, if your presenter listens to changes in the Model (for example the Model implements INotifyPropertyChanged) and your Presenter needs to react on such changes, it's better that your Presenter handles directly the PropertyChanged event of the Model instead of diverting such events through the Event Aggregator. So, if both the sender and receiver are in the same unit, there's no need to "broadcast" such events to the whole application.
I hope this answers your question.

Message passing in a plug-in framework

First off, there's a bit of background to this issue available on my blog:
http://www.codebork.com/coding/2008/06/25/message-passing-a-plug-framework.html
http://www.codebork.com/coding/2008/07/31/message-passing-2.html
I'm aware that the descriptions aren't hugely clear, so I'll try to summarise what I'm attempting as best I can here. The application is a personal finance program. Further background on the framework itself is available at the end of this post.
There are a number of different types of plug-in that the framework can handle (e.g., accounts, export, reporting, etc.). However, I'm focussing on one particular class of plug-in, so-called data plug-ins, as it is this class that is causing me problems. I have one class of data plug-in for accounts, one for transactions, etc.
I'm midway through a vast re-factoring that has left me with the following architecture for data plug-ins:
The data plug-in object (implementing intialisation, installation and plug-in metadata) [implements IDataPlugin<FactoryType>]
The data object (such as an account) [implements, e.g., IAccount]
A factory to create instances of the data object [implements, e.g., IAccountFactory]
Previously the data object and the plug-in object were combined into one, but this meant that a new transaction plug-in had to be instantiated for each transaction recorded in the account which caused a number of problems. Unfortunately, that re-factoring has broken my message passing. The data object implements INotifyPropertyChanged, and so I've hit a new problem, and one that I'm not sure how to work around: the plug-in object is registering events with the message broker, but it's the data objects that actually fire the events. This means that the subscribing plug-in currently has to subscribe to each created account, transaction, etc.! This is clearly not scalable.
As far as I can tell at the moment I have two possible solutions:
Make the data plug-in object a go-between for the data-objects and message broker, possibly batching change notifications. I don't like this because it adds another layer of complexity to the messaging system that I feel I should be able to do without.
Junk the current event-based implementation and use something else that's more easily manageable (in-memory WCF?!).
So I guess I'm really asking:
How would you solve this problem?
What potential solutions do you think I've overlooked?
Is my approach even vaguely on-track/sensible?! :-)
As you will be able to tell from the dates of the blog posts, some variant of this problem has been taxing me for quite a long time now! As such, any and all responses will be greatly appreciated.
The background to the framework itself is as follows:
My plug-in framework consists of three main components: a plug-in broker, a preferences manager and a message broker. The plug-in broker does the bread-and-butter plug-in stuff: discovering and creating plug-ins. The preferences manager manages user preferences for the framework and individual plug-ins, such as which plug-ins are enabled, where data should be saved, etc. Communication is via publish/subscribe, with the message broker sitting in the middle, gathering all published message types and managing subscriptions. The publish/subscribe is currently implemented via the .NET INotifyPropertyChanged interface, which provides one event called PropertyChanged; the message broker builds a list of all plug-ins implementing INotifyPropertyChanged and subscribes other plug-ins this event. The purpose of the message passing is to allow the account and transaction plug-ins to notify the storage plug-ins that data has changed so that it may be saved.
Wow! Big question! :)
Correct me if I'm wrong. Your basic solution now is kind of an Observer pattern, where the data object (Account, etc) notifies about changes in their states. You think that the problem is that the subscribing plugin has to register in every object to be able to handle notifications.
That's not a problem per se, you can put the event control in the Domain Model, but I suggest you create a Service Layer and do this event notifications in this layer. That way just one object would be responsible for publishing notifications.
Martin Fowler have a series of Event Patterns in his blog. Check it out! Very good reading.
This is my understanding of your question: You have a plugin object that may have to listen for events on x data objects - you don't want to subscribe to the event on each data object though. I'm assuming that several plugins may want to listen to events on the same data object.
You could create a session type object. Each plugin listens for events on the session object. The data object no longer raises the event - it calls the session object to raise the event (one of the parameters would have to be the data object raising the event).
That means that your plugins only have to subscribe to one event, but they get the event from all data objects.
On the other hand, if only one plugin will ever listen to a data object at a time, why not just have the data object call the plugin directly?
It's early yet, but have you considered trying to use MEF instead of rolling your own?

Categories