Implementing the Mediator in your application should be very straight forward, simply create an instance of the mediator, register message receivers (Message Sinks) and publish messages. The mediator will handle the distribution of messages to the various sinks that are capable of handling it.
A message sink can be a Method, or a Property:
All Message Sinks must have one of the following signatures to be able to participate in message mediation:
Specific Messages are defined by a Token, and a ParameterType.
The Token of the message is an object that represents the actual message. I find myself typically using strings that I define as constants in the various namespaces of my applications. This helps me add an element of scope to where the messages are accessible, and helps organize the messages used in an application. But of course any object is valid to use as a Token.
The ParameterType of the message is the type of object that is passed to the Publish method when a message is sent. The Mediator will find all the sinks that are listening for the Token, and have a matching ParameterType, and will pass the parameter to them. If a parameter in a sink is an Interface, or Base Class, then any parameter that implements, or inherits the Interface, or Base Class will also be sent to the sink.
Whew! If you're still reading this, then you probably want to see how you can implement it in your project!
Subscribing to receive messages.
There are several ways to subscribe to messages, you can choose the ones that best fit your specific requirements/architecture.
1. Decorate Properties/Methods in a class with the MediatorMessageSink Attribute. and subscribe each instance of the class. Click Here to See Example
2. Subscribe with a Token, Target object, and Method Name. Click Here to See Example
3. Subscribe with a Token, Target object, and MethodInfo from reflection. Click Here to See Example
4. Subscribe with a Token, and Action<TParam>. Click Here to See Example
5. Subscribe with a Token, Target object and Func<TParam, TResult>. Click Here to See Example
Publishing messages.
1. Publish a message to all sinks with a Token, and a Parameter. Click Here to See Example
2. Publish a message to all sinks with a Token, Parameter, and Callback Action<TResult>. (The callback will be called for each subscriber that returns a Type that is assignable to TResult) Click Here to See Example
3.Publish a message to all sinks with a Token, and Parameter, and return an IEnumerable<TResult> that contains the output of each subscriber that is assignable to TResult. Click Here to See Example
Special Mediator Tokens
In addition to subscribing to custom tokens, you can subscribe to 2 special mediator tokens, and receive messages when any message is published, or when a sink is registered: