Skip to content

Instantly share code, notes, and snippets.

@kevinobee
Created October 21, 2012 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinobee/3927364 to your computer and use it in GitHub Desktop.
Save kevinobee/3927364 to your computer and use it in GitHub Desktop.
using System;
using Mvc.Infrastructure;
using Mvc.Infrastructure.Sitecore.Events;
namespace Mvc.Website.layouts.Event_Sublayouts
{
public partial class Sample_Event_Consumer : System.Web.UI.UserControl, ISubscriber<FooHappened>
{
// private EventHandler m_handler;
// protected void Page_Load(object sender, EventArgs e)
// {
// m_handler = new EventHandler(ResultHandler);
// Sitecore.Events.Event.Subscribe("custom:searchresults", m_handler);
// }
// protected void Page_Unload(object sender, EventArgs args)
// {
// if (m_handler != null)
// Sitecore.Events.Event.Unsubscribe("custom:searchresults",
// m_handler);
// }
// protected void ResultHandler(object sender, EventArgs args)
// {
// var customArgs = Sitecore.Events.Event.ExtractParameter(args, 0)
// as CustomEventArgs;
// ResultsDetail.Text = "Item count = " + customArgs.Items.Length;
// Results.Text = customArgs.Timestamp.ToLongTimeString();
// }
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
MvcApplication.EventAggregator.Subscribe(this);
}
public void OnEvent(FooHappened fooEvent)
{
ResultsDetail.Text = "Item count = " + fooEvent.Items.Length;
Results.Text = fooEvent.Timestamp.ToLongTimeString();
}
}
}
@kevinobee
Copy link
Author

Any thoughts on why not to use Event Aggregator pattern over Sitecore Events?

Commented out code shows consumer wiring up event handler and giving back resources if execution completed cleanly. Exception handler (not implemented) would need to also unsubscribe from event to prevent memory leaks.

Uncommented code shows use of Event Aggregator pattern from consumer perspective. Much cleaner and with the ISubscriber declaration more assertive. Event Aggregator implementation uses WeakReference class to deal with memory management. Forgive the use of the static EventAggregator, for simplicity DI was left out.

Interested to hear in what scenarios Sitecore events would win out over using the Event Aggregator pattern.

@kevinobee
Copy link
Author

@rauljmz this is a before / after example of the consumer end of the Event Aggregator pattern that we looked at.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment