I\'m often encountering a situation where I must decide where to subscribe to events of the inner object?
For example, I have an object model looks like this:
You might be interested in an event aggregator.
What it basically does is decoupling the publishers from subscribers - it's kind of a event container. You could get the event aggregator through dependency injection (e.g. MEF) for each class you'd like to subscribe or publish from.
The way I personally use and like it the most, is the way Rob Eisenberg implemented the event aggregator in Caliburn Micro:
In your case object A, B and C would share the same instance of an event aggregator, which means as soon as events are published on this event aggregator, all these objects recognize it. Class A, B and C are able behave differently, caused by different handling of certain events.
EDIT
The use of an event aggregator is, that you subscribe to the aggregator itself with an instance of a class. The connection between publisher and subscriber class happens through relying to the same instance of the event aggregator. In case of Caliburn.Micro subscription to certain events happens through implementing a generic interface (IHandle<>
).
For example: if you'd like to subscribe to MyCustomEvent
you implement the IHandle<MyCustomEvent>
interface in the class to be subscribed.
This requires an implementation of the void Handle(MyCustomEvent e)
method from the IHandle<MyCustomEvent>
interface for this type of event. This method gets called everytime a (new) MyCustomEvent
is published on the shared event aggregator.
There is way too much public
stuff in your example. Hope I'll make sense below:
#2 and #3 are not good: ClassC should handle and implement the events, handling them and letting them "bubble up" (invoking their own, same, event) for ClassD to handle correctly.
Basically, all of them should handle all events, either reacting to them (as in ClassB to ClassA's events) or just propagating them.
Find nice solution here:
Csharp-NotificationCenter