Where to subscribe to events of the inner object?

后端 未结 3 1560
爱一瞬间的悲伤
爱一瞬间的悲伤 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 interface in the class to be subscribed. This requires an implementation of the void Handle(MyCustomEvent e) method from the IHandle interface for this type of event. This method gets called everytime a (new) MyCustomEvent is published on the shared event aggregator.

提交回复
热议问题