<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dude, where is my Kaizen? &#187; Publish &amp; subscribe</title>
	<atom:link href="http://www.bjoernrochel.de/tag/publish-subscribe/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bjoernrochel.de</link>
	<description>Björn Rochel&#039;s weblog</description>
	<lastBuildDate>Mon, 21 Jun 2010 07:26:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Yet another way to do publish &amp; subscribe Part III . . .</title>
		<link>http://www.bjoernrochel.de/2008/07/07/yet-another-way-to-do-publish-subscribe-part-iii/</link>
		<comments>http://www.bjoernrochel.de/2008/07/07/yet-another-way-to-do-publish-subscribe-part-iii/#comments</comments>
		<pubDate>Mon, 07 Jul 2008 14:42:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Publish & subscribe]]></category>

		<guid isPermaLink="false">http://bjro.de/2008/07/07/yet-another-way-to-do-publish-subscribe-part-iii/</guid>
		<description><![CDATA[Today, I discuss the design of what I actually implemented. Please be aware that I do not claim that it&#8217;s the perfect solution to the concept at hand. It&#8217;s what I&#8217;ve come up with to implement it, which at least for my context works very well. With that being said, let&#8217;s dive into the design.
The [...]]]></description>
			<content:encoded><![CDATA[<p align="left">Today, I discuss the design of what I actually implemented. Please be aware that I do not claim that it&#8217;s the perfect solution to the concept at hand. It&#8217;s what I&#8217;ve come up with to implement it, which at least for my context works very well. With that being said, let&#8217;s dive into the design.</p>
<p>The core of the design is formed by a class called <strong>Subscription</strong>.</p>
<p><img src="http://www.bjoernrochel.de/wp-content/uploads/2008/07/subscription.jpg" alt="PubSub.Subscription" /></p>
<p>The name is quite self describing, but let me say some words about its intended purpose in my publish &amp; subscribe implementation. The subscription is used as an endpoint for sending messages to a subscriber, hiding away the thread context (<strong>SynchronizationContext</strong>) of the related subscriber instance and the weak reference handling to the related subscriber instance from the caller. It&#8217;s a kind of mediator instance so to say. Besides that it provides some information about which message type the subscription is for.Subscriptions are created by an implementation of the <strong>ISubscriptionAssembler </strong>interface. As the name implies the main responsibility of this interface is to create subscriptions either in an explicit (create a single subscription for a given <strong>ISubscriber&lt;TMessage&gt;</strong> instance) or implicit (infer all subscriptions of a given instance / type) manner . . .</p>
<p style="text-align: center"><a href="http://www.bjoernrochel.de/wp-content/uploads/2008/07/isubscriptionassembler.jpg"><img class="alignnone size-medium wp-image-11" title="PubSub.ISubscriptionAssembler" src="http://www.bjoernrochel.de/wp-content/uploads/2008/07/isubscriptionassembler.jpg" alt="" width="242" height="129" /></a></p>
<p>The current implementation (<strong>SubscriptionAssembler</strong>) uses a small wrapper around <strong>SynchronizationContext </strong>called <strong>SyncFactory </strong>to capture the thread context while building the subscription. All this factory does is that it registers a new <strong>SynchronizationContext </strong>via <strong>SyncronizationContext.Current</strong> when no context exists. This is especially useful when doing unit testing (which by default has no <strong>SynchronizationContext</strong> set).</p>
<p>Besides that the <strong>SubscriptionAssembler </strong>provides functionality to infer all subscriptions of a particular type and / or instance via reflection. This is done on top of the classes <strong>SubscriptionInspector </strong>and <strong>MessageInterestCache</strong>. The <strong>SubscriptionInspector </strong>realizes the relflection part, while the <strong>MessageInterestCache </strong>serves as a small cache for optimizing the performance of the assembler (message interests are only reflected once). Also included is a bit of functionality which can be used to pre-infer the message interests of a particular type, which might get handy when integrating with an InversionOfControl-container (most IoC-container split registration and type construction).</p>
<p>Once subscriptions have been created, they are managed by an implementation of the <strong>ISubscriptionManager </strong>interface. This means:</p>
<ol>
<li>Tracking all subscriptions for a particular message type (with operations for adding / releasing and retrieving subscriptions for a particular message type).</li>
<li>Detecting and removing dead references (garbage collected instances).</li>
</ol>
<p style="text-align: center" align="left"><a href="http://www.bjoernrochel.de/wp-content/uploads/2008/07/isubscriptionmanager.jpg"><img class="alignnone size-medium wp-image-12" title="PubSub.ISubscriptionManager" src="http://www.bjoernrochel.de/wp-content/uploads/2008/07/isubscriptionmanager.jpg" alt="" /></a></p>
<p>The actual <strong>IMessageBus </strong>implementation called <strong>MessageBus </strong>is implemented only as a small wrapper around the <strong>ISubscriptionAssembler </strong>(for creating subscriptions) and the <strong>ISubscriptionManager </strong>(for adding and removing subscriptions explicitly). Here you can impression what it actually does:</p>
<pre class="brush: csharp">
public class MessageBus : IMessageBus
{
        private readonly ISubscriptionManager _SubscriptionManager;
        private readonly ISubscriptionAssembler _SubscriptionAssembler;

        public MessageBus(
            ISubscriptionManager subscriptionManager,
            ISubscriptionAssembler subscriptionAssembler)
        {
            Ensure.ArgumentIsNotNull(subscriptionManager, &quot;subscriptionManager&quot;);
            Ensure.ArgumentIsNotNull(subscriptionAssembler, &quot;subscriptionAssembler&quot;);

            _SubscriptionManager = subscriptionManager;
            _SubscriptionAssembler = subscriptionAssembler;
        }

        public void AddSubscriber(ISubscriber subscriber) where TMessage : class
        {
            Ensure.ArgumentIsNotNull(subscriber, &quot;subscriber&quot;);

            Subscription subscription = _SubscriptionAssembler.CreateSingle(subscriber);
            _SubscriptionManager.Add(subscription);
        }

        public void ReleaseSubscriber(ISubscriber subscriber) where TMessage : class
        {
            Ensure.ArgumentIsNotNull(subscriber, &quot;subscriber&quot;);

            _SubscriptionManager.ReleaseSubscription(subscriber);
        }

        public void SendMessage(TMessage message) where TMessage : class
        {
            Ensure.ArgumentIsNotNull(message, &quot;message&quot;);

            var subscriptions = _SubscriptionManager.GetSubscriptions(message.GetType());

            foreach (Subscription subscription in subscriptions)
            {
                subscription.SendMessage(message);
            }
        }
}
</pre>
<p>The interface to an InversionOfControl-container is the <strong>IocBridge</strong>.  This class is just a small mediator that can be used in combination with the extension method the container provides. It provides simple access points which call an <strong>ISubscriptionAssembler </strong>implementation, when an instance has been configured, try to infer all subscriptions when a new instance has been created and that release all subscriptions related to a particular instance when the instance has been removed from the container.</p>
<p style="text-align: center"><a href="http://www.bjoernrochel.de/wp-content/uploads/2008/07/iocbridge.jpg"><img class="alignnone size-medium wp-image-10" title="PubSub.IocBridge" src="http://www.bjoernrochel.de/wp-content/uploads/2008/07/iocbridge.jpg" alt="" width="242" height="145" /></a></p>
<p>Regarding the design of the publish &amp; subscribe system that&#8217;s all there is to tell <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  .  Here is a little overview over all classes.</p>
<p><a title="PubSub.Overview" href="http://www.bjoernrochel.de/wp-content/uploads/2008/07/overview.jpg"></a></p>
<p style="text-align: center"><a title="PubSub.Overview" href="http://www.bjoernrochel.de/wp-content/uploads/2008/07/overview.jpg"><img src="http://www.bjoernrochel.de/wp-content/uploads/2008/07/overview.jpg" alt="PubSub.Overview" width="496" height="323" /></a></p>
<p>In the last post I mentioned that my favourite IoC-container is Castle Windsor. In order to use the library there still is a little piece missing. I&#8217;ve integrated it with the WindsorContainer by implementing an IFacility.</p>
<pre class="brush: csharp">
public class PubSubFacility : AbstractFacility
{
        private IIocBridge _IocBridge;

        protected override void Init()
        {
            _IocBridge = Kernel.Resolve&lt;IIocBridge&gt;();
            Kernel.ComponentModelCreated += OnComponentModelCreated;
            Kernel.ComponentCreated += OnComponentCreated;
            Kernel.ComponentDestroyed += OnComponentDestroyed;
        }

        private void OnComponentDestroyed(ComponentModel model, object instance)
        {
            _IocBridge.UninstallInstance(instance);
        }

        private void OnComponentCreated(ComponentModel model, object instance)
        {
            _IocBridge.TryInstallInstance(instance);
        }

        private void OnComponentModelCreated(ComponentModel model)
        {
            _IocBridge.TryTypeInstallation(model.Implementation);
        }
}
</pre>
<p>Together with some xml the whole stuff can easily be wired together.</p>
<pre class="brush: xml">
&lt;castle&gt;
&lt;components&gt;
&lt;facilities&gt;
&lt;facility
id=&quot;PubSubFacility&quot;
type=&quot;BjRo.CastleContrib.PubSub.PubSubFacility,
BjRo.CastleContrib.PubSub&quot; /&gt;
&lt;/facilities&gt;

&lt;component id=&quot;PubSubFacade&quot;
type=&quot;BjRo.PubSub.IocBridge, BjRo.PubSub&quot;
service=&quot;BjRo.PubSub.IIocBridge, BjRo.PubSub&quot;
lifestyle=&quot;Singleton&quot; /&gt;

&lt;component id=&quot;MessageBus&quot;
type=&quot;BjRo.PubSub.MessageBus, BjRo.PubSub&quot;
service=&quot;BjRo.PubSub.IMessageBus, BjRo.PubSub&quot;
lifestyle=&quot;Singleton&quot; /&gt;

&lt;component id=&quot;SubscriptionAssembler&quot;
type=&quot;BjRo.PubSub.SubscriptionAssembler, BjRo.PubSub&quot;
service=&quot;BjRo.PubSub.ISubscriptionAssembler, BjRo.PubSub&quot;
lifestyle=&quot;Singleton&quot; /&gt;

&lt;component id=&quot;SubscriptionManager&quot;
type=&quot;BjRo.PubSub.SubscriptionManager, BjRo.PubSub&quot;
service=&quot;BjRo.PubSub.ISubscriptionManager, BjRo.PubSub&quot;
lifestyle=&quot;Singleton&quot; /&gt;
&lt;/components&gt;
&lt;/castle&gt;
</pre>
<p>That&#8217;s it with my take on (local) publish &amp; subscribe. It may not be perfect but it suits my needs at the moment. I&#8217;m planning to integrate the standard .NET APM in the <strong>IMessageBus </strong>interface in order allow asynchronous message sending and the common rendezvous techniques. I&#8217;m looking forward to any feedback for my solution and would like to share the code under some OS license, if someone is interested in. . . </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/07/07/yet-another-way-to-do-publish-subscribe-part-iii/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Yet another way to do publish &amp; subscribe Part II . . .</title>
		<link>http://www.bjoernrochel.de/2008/07/02/yet-another-way-to-do-publish-subscribe-part-ii/</link>
		<comments>http://www.bjoernrochel.de/2008/07/02/yet-another-way-to-do-publish-subscribe-part-ii/#comments</comments>
		<pubDate>Wed, 02 Jul 2008 16:21:03 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Publish & subscribe]]></category>

		<guid isPermaLink="false">http://bjro.de/2008/07/02/yet-another-way-to-do-publish-subscribe-part-ii/</guid>
		<description><![CDATA[As promised on the last post, this time I talk more about what I actually implemented. Let&#8217;s start with the basic API. The whole API is very simple and message centered. In order to be able to recieve messages you have to implement the ISubscriber&#60;TMessage&#62; interface.

public interface ISubscriber&#60;TMessage&#62;
{
     void Handle(TMessage message);
}

The [...]]]></description>
			<content:encoded><![CDATA[<p>As promised on the last post, this time I talk more about what I actually implemented. Let&#8217;s start with the basic API. The whole API is very simple and message centered. In order to be able to recieve messages you have to implement the <strong>ISubscriber&lt;TMessage&gt;</strong> interface.</p>
<pre class="brush: csharp">
public interface ISubscriber&lt;TMessage&gt;
{
     void Handle(TMessage message);
}
</pre>
<p>The generic parameter <strong>TMessage </strong>specifies the type of message the subscriber is interested in.Â  The message should simply be implemented by a POCO. Examples could be:</p>
<ul>
<li>ISubscriber&lt;ActivePatientChanged&gt;</li>
<li>ISubscriber&lt;ApplicationTitleChanged&gt;</li>
<li>ISubscriber&lt;CsvExportFinished&gt;</li>
</ul>
<p>A consumer class wants to publish messages or to register itsself for a particular message needs to have a reference to an <strong>IMessageBus </strong>implementation. This interface serves as a consumer side facade to the pubsub system.</p>
<pre class="brush: csharp">
public interface IMessageBus
{
      void AddSubscriber(ISubscriber subscriber);
      void ReleaseSubscriber(ISubscriber subscriber);
      void SendMessage&lt;TMessage&gt;(TMessage message);
}
</pre>
<p>From a consumer perspective that&#8217;s all your need to known when dealing with publish &amp; subscribe. Together with type inference it&#8217;s event nicer to use <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<pre class="brush: csharp">
public class DemoMessage
{
}

public class MyListener : ISubscriber&lt;DemoMessage&gt;
{
     public void Subscribe(IMessageBus bus)
     {
          bus.AddSubscriber(this);
     }

     public void Handle(DemoMessage message)
     {
     }
}

public class MyPublisher
{
     private IMessageBus _Bus;

     public MyPublisher(IMessageBus bus)
     {
          _Bus = bus;
     }

     public void Demo()
     {
         _Bus.SendMessage(new DemoMessage());
     }
}
</pre>
<p>Some other characteristics also worth mentioning:</p>
<ul>
<li>The current implementation captures the thread context when a subscriber is registered. All callbacks will be handled on the same thread on which they were registered.</li>
<li>Only a weak reference is held to the subscriber. This guarantees that a subscriber can be garbage collected although not properly unregistered from the publish &amp; subscribe system. The implementation detects dead references and removes them automatically.</li>
</ul>
<p>With that beeing said I would like too conclude the series about publish &amp; subscribe with a post about the actual implementation which will follow up . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/07/02/yet-another-way-to-do-publish-subscribe-part-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Yet another way to do publish &amp; subscribe . . .</title>
		<link>http://www.bjoernrochel.de/2008/06/30/yet-another-way-to-do-publish-subscribe/</link>
		<comments>http://www.bjoernrochel.de/2008/06/30/yet-another-way-to-do-publish-subscribe/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 20:01:15 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CAB]]></category>
		<category><![CDATA[Publish & subscribe]]></category>

		<guid isPermaLink="false">http://bjro.de/2008/06/30/yet-another-way-to-do-publish-subscribe/</guid>
		<description><![CDATA[About 2,5 years ago I first came across the idea of combining dependency injection with loosly coupled publish &#38; subscribe. This was when I inspected the source code of the Composite Application Block (CAB) with its underlying InversionOfControl-container ObjectBuilder from Microsoft.
What I liked about publish &#38; subscribe in CAB:

The automatic thread marshalling. (Basically you&#8217;re able [...]]]></description>
			<content:encoded><![CDATA[<p>About 2,5 years ago I first came across the idea of combining dependency injection with loosly coupled publish &amp; subscribe. This was when I inspected the source code of the <a href="http://msdn.microsoft.com/en-us/library/aa480450.aspx">Composite Application Block (CAB)</a> with its underlying InversionOfControl-container ObjectBuilder from Microsoft.</p>
<p>What I liked about publish &amp; subscribe in CAB:</p>
<ul>
<li>The automatic thread marshalling. (Basically you&#8217;re able to specify whether the subscription-callback will be handled on the UI-thread or the same thread as the publisher)</li>
<li>The wiring was done during the build process in the ObjectBuilder. Publishers and Subscribers are completely decoupled. Wow, this was pretty amazing for me when I discovered that late 2005 <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</li>
</ul>
<p>What I didn&#8217;t like about it:</p>
<ul>
<li>It is very tightly coupled to a CAB internal data structure called WorkItem. (Not reusable outside the scope of CAB)</li>
<li>It uses standard .NET events / delegates. (The publisher needed to define an event and the subscriber needed to have a public method with a matching  &#8220;object-sender-eventargs-e&#8221; &#8211; signature.)</li>
<li>It uses attributes and especially a string based topic identifier to correlate publishers for a topic and corresponding subscribers. (Maybe I&#8217;m narrow-minded on this, but I think the simplest way to specify a subscription is the best, which imho is expressing a subscription by implementing an interface.)</li>
</ul>
<p>Many frameworks or libraries I looked into over time mostly followed a comparable approach using either events or some other delegate-based solution (the EventBroker in CAB, the EventBrokerFacility in Castle Windsor, the EventAggregator in PRISM, &#8230;.) (Please correct me if I overlooked or misunderstood something <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> ). The only framework I came across with something similar to what I had in mind is <a href="http://devlicio.us/blogs/rob_eisenberg/archive/2008/01/07/introducing-caliburn-an-mvc-mvp-wpf-framework.aspx">Caliburn</a>.</p>
<p>Unfortunately Caliburn is a WPF/ .NET 3.0 based framework, but most of the products of my current employer are limited to .NET 2.0 due to a minimum  system requirement of Windows 2k. Because of that I decided to implement something similar for our purposes which can be easily integrated into the InversionOfControl &#8211; container of our choice (which is Castle Windsor at the moment, by the way <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ).</p>
<p>I&#8217;ll be describing the implementation and publish the source code for anyone who is interested in one or more follow-up posts . . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/06/30/yet-another-way-to-do-publish-subscribe/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
