Language: C#
Simple Message Broker using MEF
namespace Nowcom.Quicksilver { public interface IMessage { } } namespace Nowcom.Quicksilver { using System.ComponentModel.Composition; using System; public interface IMessageMetadata { Type MessageType { get; } } [MetadataAttribute] [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)] public class SubscribeToMessage: ExportAttribute { public Type MessageType { get; set;} public SubscribeToMessage(Type messageType):base(typeof(Delegate)) { MessageType = messageType; } } } namespace Nowcom.Quicksilver { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; [Export(typeof(MessengerService))] public class MessengerService { [ImportMany(typeof(Delegate), AllowRecomposition = true)] public List<ExportFactory<Delegate, IMessageMetadata>> Subscribers { get; set; } public void Publish<T>() where T : class, IMessage { GetDelegateList<T>().ForEach(factory => Invoke(factory, null)); } public void Publish<T>(params object[] parameters) where T : class, IMessage { GetDelegateList<T>().ForEach(factory => Invoke(factory, parameters)); } private List<ExportFactory<Delegate, IMessageMetadata>> GetDelegateList<T>() where T : class, IMessage { return Subscribers.Where(import => import.Metadata.MessageType.IsAssignableFrom(typeof(T))).ToList(); } private static void Invoke(ExportFactory<Delegate, IMessageMetadata> factory, params object[] parameters) { using (var export = factory.CreateExport()) { export.Value.Method.Invoke(export.Value.Target, parameters); } } } } /* Test */ namespace Testing { using System.ComponentModel.Composition.Hosting; using Nowcom.Quicksilver; using Microsoft.VisualStudio.TestTools.UnitTesting; public interface ISimpleMessage : IMessage { } public class Test { private CompositionContainer _Container; private bool _Result; public void Setup() { var catalog = new TypeCatalog(typeof(MessengerService)); _Container = new CompositionContainer(catalog); } [SubscribeToMessage(typeof(ISimpleMessage))] public void TestSubscription(bool parameter) { _Result = parameter; } [TestMethod] public void WhenMessageIsPublished() { Setup(); _Result = false; var messengerService = _Container.GetExportedValue<MessengerService>(); messengerService.Publish<ISimpleMessage>(true); Assert.IsTrue(_Result); } } }
Tags:
Description:
This is a simple Message broker using MEF that does the same kind of thing like EventAggregator from Prism. Not as complicated and not as powerful either.
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

