Skip to content

Instantly share code, notes, and snippets.

@troufster
Created April 26, 2012 20:18
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 troufster/2502766 to your computer and use it in GitHub Desktop.
Save troufster/2502766 to your computer and use it in GitHub Desktop.
Event driven architecture
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var sub = new TrivialSubscriptionService();
sub.Subscribe<FooCommand>(new FooCommandListener());
IEventPublisher publisher = new EventPublisher(sub);
publisher.Publish(new FooCommand { Message = "God dag!" });
}
}
public class FooCommand {
public string Message {get; set; }
}
public class FooCommandListener : ISubscribeTo<FooCommand> {
public void Process(FooCommand @event)
{
Debug.WriteLine(@event.Message);
}
}
#region framework
public interface ISubscriptionService {
IEnumerable<object> GetSubscribers<T>();
void Subscribe<T>(ISubscribeTo<T> subtype) where T : class;
}
public class TrivialSubscriptionService : ISubscriptionService {
private IDictionary<Type, IList<object>> _subscriptions;
public TrivialSubscriptionService() {
_subscriptions = new Dictionary<Type, IList<object>>();
}
public IEnumerable<object> GetSubscribers<T>()
{
IList<object> res;
if (_subscriptions.TryGetValue(typeof(T), out res)) {
return res;
}
return null;
}
public void Subscribe<T>(ISubscribeTo<T> subtype) where T : class
{
if (_subscriptions.ContainsKey(typeof(T)))
{
_subscriptions[typeof(T)].Add(subtype);
}
else {
var list = new List<object>() { subtype };
_subscriptions.Add(new KeyValuePair<Type,IList<object>>(typeof(T), list));
;
}
}
}
public interface IEventPublisher {
void Publish<T>(T @event) where T : class;
}
public interface ISubscribeTo<T> where T:class {
void Process(T @event);
}
public class EventPublisher : IEventPublisher {
private readonly ISubscriptionService _subService;
public EventPublisher(ISubscriptionService subservice) {
_subService = subservice;
}
public void Publish<T>(T @event) where T : class
{
var subs = _subService.GetSubscribers<T>();
subs.ToList()
.ForEach(
s => PublishToConsumer((ISubscribeTo<T>)s, @event as T)
);
}
private void PublishToConsumer<T>(ISubscribeTo<T> s, object @event) where T : class
{
s.Process(@event as T);
}
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment