Where to subscribe to events of the inner object?

后端 未结 3 1530
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 12:35

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:

相关标签:
3条回答
  • 2021-01-14 13:06

    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:

    • NuGet Gallery
    • Caliburn.Micro Event Aggregator Documentation

    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.

    0 讨论(0)
  • 2021-01-14 13:16

    There is way too much public stuff in your example. Hope I'll make sense below:

    1. ClassB contains an object of type ClassA, and handles some ClassA events
    2. ClassC contains an object of type ClassB but events are ignored.
    3. ClassD contains an object of type ClassC and handles events from the ClassA object inside the ClassB object contains in this ClassC objects

    #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.

    0 讨论(0)
  • 2021-01-14 13:18

    Find nice solution here:

    Csharp-NotificationCenter

    0 讨论(0)
提交回复
热议问题