Created
April 26, 2012 20:18
-
-
Save troufster/2502766 to your computer and use it in GitHub Desktop.
Event driven architecture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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