Allow Mediator.Register to accept Action / Lambda for easier registering


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.
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.
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.
Closed Nov 27, 2011 at 6:15 PM by sachabarber
Not an issue


jgable wrote Oct 18, 2009 at 10:13 PM

I've uploaded a patch. Thanks for your great framework.

wrote Dec 6, 2009 at 8:45 AM

sachabarber wrote May 2, 2010 at 7:31 AM

I should be allowing this very shortly in Cinch

sachabarber wrote May 4, 2010 at 9:24 AM

I have done that, but if you use that lambda registration you WILL have to unregister yourself. Bur I have added that in

wrote Nov 27, 2011 at 6:15 PM

wrote Feb 22, 2013 at 12:07 AM

wrote May 16, 2013 at 11:46 AM