<?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; Inversion of Control</title>
	<atom:link href="http://www.bjoernrochel.de/tag/inversion-of-control/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>Pimp my CAB, or how to integrate an existing IoC with SCSF</title>
		<link>http://www.bjoernrochel.de/2009/08/31/pimp-my-cab-or-how-to-integrate-an-existing-ioc-with-scsf/</link>
		<comments>http://www.bjoernrochel.de/2009/08/31/pimp-my-cab-or-how-to-integrate-an-existing-ioc-with-scsf/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 19:14:53 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[CompositeApps]]></category>
		<category><![CDATA[CAB]]></category>
		<category><![CDATA[Inversion of Control]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=531</guid>
		<description><![CDATA[A LITTLE WARNING: This post goes pretty deep into the CAB framework without examining the CAB basics. If you&#8217;re unfamiliar with CAB or SCSF this post is probably not going to be very handy for you . . . 
My current project uses the Smart Client Software Factory which is build on top of the [...]]]></description>
			<content:encoded><![CDATA[<p>A LITTLE WARNING: This post goes pretty deep into the CAB framework without examining the CAB basics. If you&#8217;re unfamiliar with CAB or SCSF this post is probably not going to be very handy for you . . . </p>
<p>My current project uses the Smart Client Software Factory which is build on top of the Composite UI Application Block from Microsofts Patterns &amp; Practices department. SCSF is an organizational standard at my current client and we&#8217;re reusing some components of earlier projects (Large Parts of the Shell, Changetracking model etc.)</p>
<p>CAB is build around a very simple Dependency Injection machinery called the ObjectBuilder. I consider having the ObjectBuilder a good thing, compared to having no Dependency Injection at all. However if you&#8217;ve ever worked with any other IoC be it StructureMap, Unity, Windsor, NInject or some other container, you&#8217;ll recognize pretty fast some limitations.</p>
<p>Its dependency injection mechanism</p>
<ul type="square">
<li>can&#8217;t really be used without attributes.</li>
<li>doesn&#8217;t separate registration and creation very well, which often leads to ordering problems.</li>
<li>can&#8217;t close open generic types. If you&#8217;ve ever used generic specialization you&#8217;re going to miss this.</li>
<li>is pretty tightly coupled to the concept of WorkItems inside CAB.</li>
</ul>
<p>The last point is actually the real pain point for me. The whole WorkItem API is way to general purpose and generic (meaning string based!!!) in many parts and actually not the kind of concept I would like to be a central piece of my application design. It&#8217;s not intuitive to work with it and imho doesn&#8217;t fall into the pit of success at all. Interestingly when you compare PRISM (which was also build by P&amp;P about two years later) to CAB you&#8217;re going to recognize that the concept of WorkItems is completely missing in PRISM. Maybe I&#8217;m not the only one who feels that way. </p>
<p>Our team decided very early that the whole contact area of our application to the CAB framework should be limited to the presentation layer. We wanted to use a fully fledged IoC on the lower layers. This lead to an intersting challenge: How to integrate those two pipelines? </p>
<p>My initial thought was to replace the CreationStrategy used in CABs Builder class with something that reaches into our main container. This turned out not to be the best choice since a lot of CABs internal structure kind of relates to the standard behavior. I got something working for about half of the use cases, but it didn&#8217;t really feel good.</p>
<p>You know the best ideas come up when you stand under the shower. At least this happened yesterday. Actually integrating those two things is pretty straight forward. I just needed to approach the problem differently.</p>
<p>CAB is build around attributes. A typical CAB service might look like this.</p>
<pre class="brush: csharp">

public class NavigationService
{
    public NavigationService([ServiceDependency] IShell shell)
    {

    }
}
</pre>
<p>The ServiceDependencyAttribute tells the ObjectBuilder that it should get the dependency from the collection of Services associated with the related WorkItem used to create the class. The interesting part is that this isn&#8217;t a marker attribute. It&#8217;s a fully fledged extension point to which the ObjectBuilder delegates the essential work of resolving an instance. </p>
<p><b>Here&#8217;s the deal: You can write a custom tailored attribute which is called by the ObjectBuilder but uses you main IoC in order to resolve the dependency</b></p>
<p>The implementation of this is actually pretty easy. Here are the steps you need to implement.</p>
<p><b>1. Create a Static Gateway into your container</b></p>
<p>Attributes are by their nature kind of static and created by the framework. In order to be able to call into my container from an attribute I created a static class which holds a reference to my container (You can of course also use the P&amp;P CommonServiceLocator for this). </p>
<pre class="brush: csharp">

public static class Container
{
    private static IContainer _container;

    public static void SetContainer(IContainer container)
    {
        _container = container;
    }

    public static void object Resolve(Type type)
    {
        return _container.Resolve(type);
    }
}
</pre>
<p><b>2. Create an attribute deriving from ParameterAttribute</b></p>
<p>The responsibility of ParameterAttributes in the ObjectBuilder is pretty limited. All they have to do is to create an implementation of the IParameter interface which will than be used to do the actual resolving. If you&#8217;re wondering what the membertype is, that&#8217;s the type of the parameter marked with the attribute (in the example code above this would be IShell). The CreateParameter method will automatically be called by the ObjectBuilder during the creation process.</p>
<pre class="brush: csharp">

public class ContainerDependencyAttribute : ParameterAttribute
{
   public override IParameter CreateParameter(Type memberType)
   {
       return new ContainerParameter(memberType);
   }
}
</pre>
<p><b>3. Create an implementation of IParameter which calls into your Static Gateway</b></p>
<p>The IParameter interface defines two methods GetParameterType and GetValue. </p>
<pre class="brush: csharp">

public interface IParameter
{
    public Type GetParameterType(IBuilderContext buildContext);
    object Getvalue(IBuilderContext buildContext);
}
</pre>
<p>We simply implement the first one with returning the member type and the the second one with a call into our Gateway.</p>
<pre class="brush: csharp">

public class ContainerParameter : IParameter
{
   private Type _typeToResolve;

   public ContainerParameter(Type typeToResolve)
   {
      _typeToResolve = typeToResolve;
   }

   public Type GetParameterType(IBuilderContext buildContext)
   {
       return _typeToResolve;
   }

   public object Getvalue(IBuilderContext buildContext)
   {
       return Container.Resolve(_typeToResolve);
   }
}
</pre>
<p><b>Here is an example how it is used</b></p>
<pre class="brush: csharp">

public class SomePresenter
{
    public SomePresenter(
         [ServiceDependency] INavigationService navigationService,
         [ContainerDependency] ISomeService someService)
    {
    }
}
</pre>
<p>At least for us, this works like a charm. What I like about the solution is that it plays nicely by the rules of the CAB framework and doesn&#8217;t fight the framework design, but still enables us to use the framework in a way we want to use it. </p>
<p>The interesting aspect in this approach is that you&#8217;re now able to haved mixed dependencies where one part is resolved using the surrounding CAB WorkItem and the other part is resolved using your container of choice. The whole attribute usage is limited to the presentation layer while the rest of the application can take advantage of fully fledged dependency injection without attribute, with generic specicialization and dynamic proxy generation, just to name a few options.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/08/31/pimp-my-cab-or-how-to-integrate-an-existing-ioc-with-scsf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>
	</channel>
</rss>
