Call me lazy, but sometimes I like to pass in a lambda expression to the Register function if I just need to do something simple in response to a Mediator message. The EventAggregator in PRISM allows this as well as passing a reference to a void method that takes one parameter.
I've added an overload to the Mediator class to allow for my lazy habits and I thought you, or someone else, would be interested in adding it to this project. Here's the code and some tests. I'll upload a patch when I have some time tonight.
/// <summary>
/// JBG - Convenience method for specifying lambda's as callbacks.
/// </summary>
/// <typeparam name="T">The type of parameter used by the callback</typeparam>
/// <param name="message">Identifies a series of callbacks</param>
/// <param name="callback">The action to perform when notified.</param>
public void Register<ParmType>(string message, Action<ParmType> callback)
{
if (callback.Target == null)
throw new InvalidOperationException("Delegate cannot be static");
// JBG - The Action<T> guarantees we have 1 and only 1 parameter.
Type parameterType = typeof(ParmType);
invocationList.AddAction(message, callback.Target,
callback.Method, parameterType);
}
/// <summary>
///A test for Register with Lambda expression.
///</summary>
[TestMethod()]
public void Should_Allow_Actions_To_Register_For_Events()
{
Mediator target = new Mediator();
string message = "testevent";
string result = string.Empty;
Action<string> callback =
(x) => result = x;
target.Register(message, callback);
Assert.AreNotEqual<string>("success", result);
target.NotifyColleagues<string>("testevent", "success");
Assert.AreEqual<string>(result, "success");
}
/// <summary>
///A test for Register with void method that takes one parameter.
///</summary>
[TestMethod()]
public void Should_Allow_Void_Methods_With_One_Parameter_To_Register_For_Events()
{
Mediator target = new Mediator();
string message = "testevent";
target.Register<string>(message, TestMethodWithString);
Assert.AreNotEqual<string>("success", _testResult);
target.NotifyColleagues<string>("testevent", "success");
Assert.AreEqual<string>(_testResult, "success");
}
private string _testResult = string.Empty;
private void TestMethodWithString(string blah)
{
_testResult = blah;
}
Hope someone else finds it useful.
Jacob