<?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>Nicholas Blumhardt &#187; Nicholas Blumhardt</title>
	<atom:link href="http://nblumhardt.com/author/admin/feed/" rel="self" type="application/rss+xml" />
	<link>http://nblumhardt.com</link>
	<description></description>
	<lastBuildDate>Fri, 28 Oct 2011 20:25:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Convention-based part registration available in a new MEF preview!</title>
		<link>http://nblumhardt.com/2011/10/convention-based-part-registration-available-in-a-new-mef-preview/</link>
		<comments>http://nblumhardt.com/2011/10/convention-based-part-registration-available-in-a-new-mef-preview/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 20:24:20 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=320</guid>
		<description><![CDATA[There are many, many similarities between IoC-for-decoupling (as we know and love in Autofac) and IoC-for-extensibility as is implemented by MEF. One thing that stuck out in the beginning for the MEF project members with IoC backgrounds, was the verbosity of using [Import] and [Export] attributes to describe parts, instead of the much more terse&#8230;]]></description>
			<content:encoded><![CDATA[<p>There are many, many similarities between IoC-for-decoupling (as we know and love in <a href='http://autofac.org'>Autofac</a>) and IoC-for-extensibility as is implemented by <a href='http://mef.codeplex.com'>MEF</a>.</p>
<p>One thing that stuck out in the beginning for the MEF project members with IoC backgrounds, was the verbosity of using <code class="codecolorer text default"><span class="text">[Import]</span></code> and <code class="codecolorer text default"><span class="text">[Export]</span></code> attributes to describe parts, instead of the much more terse convention-driven approach used by IoC containers.</p>
<p>Over time, most of us grew to appreciate the role that the attributed programming model played in creating an unambiguous, decentralized configuration mechanism for plug-ins.</p>
<p>What the we also found was that applications using MEF for extensibility would also use it for internal composition, a-la IoC. In the much more controlled context of the host application, the lighter, more direct, convention-driven configuration model is compelling. DRY is one of the most important principles for building maintainable software, so techniques that eliminate repetition are very valuable.</p>
<p>It should be no surprise then, that the latest release of MEF (that I’ve only recently had any involvement in) comes with a nifty little model for defining parts by convention. The syntax should be familiar if you’re used to this kind of API:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">var builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> RegistrationBuilder<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
builder<span style="color: #008000;">.</span><span style="color: #0000FF;">ForTypesDerivedFrom</span><span style="color: #008000;">&lt;</span>Controller<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">.</span><span style="color: #0000FF;">Export</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">.</span><span style="color: #0000FF;">SetCreationPolicy</span><span style="color: #008000;">&#40;</span>CreationPolicy<span style="color: #008000;">.</span><span style="color: #0000FF;">NonShared</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></div></div>
<p>When wired up to a MEF catalog, these simple conventions will read a part like:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> HomeController <span style="color: #008000;">:</span> &nbsp;Controller<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> HomeController<span style="color: #008000;">&#40;</span><span style="color: #008080; font-style: italic;">/* Dependencies here */</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> … <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> ActionResult Index<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> … <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>As:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #008000;">&#91;</span>Export, PartCreationPolicy<span style="color: #008000;">&#40;</span>CreationPolicy<span style="color: #008000;">.</span><span style="color: #0000FF;">NonShared</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span><br />
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> HomeController <span style="color: #008000;">:</span> &nbsp;Controller<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#91;</span>ImportingConstructor<span style="color: #008000;">&#93;</span><br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> HomeController<span style="color: #008000;">&#40;</span><span style="color: #008080; font-style: italic;">/* Dependencies here */</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> … <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> ActionResult Index<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> … <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p><code class="codecolorer text default"><span class="text">RegistrationBuilder</span></code> has more than a few tricks up its sleeve, and we expect to write a lot more about it on the <a href='http://blogs.msdn.com/b/bclteam/'>BCL team blog</a> in the coming weeks. For now, you can <a href='http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx'>read about the new release</a>, or even better, <a href='http://mef.codeplex.com/releases/view/75766'>download the preview source and binaries</a> from CodePlex.</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/10/convention-based-part-registration-available-in-a-new-mef-preview/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Autofac 2.5 Released</title>
		<link>http://nblumhardt.com/2011/07/autofac-2-5-released/</link>
		<comments>http://nblumhardt.com/2011/07/autofac-2-5-released/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 22:53:23 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=312</guid>
		<description><![CDATA[Autofac 2.5 is now available on the project site and via NuGet. The new version includes a range of great contributions. After incubation as an external project, Windows Phone 7 now joins ranks of officially-supported targets (just install the Autofac package via NuGet and you&#8217;re up and running!) For some tips on getting started see&#8230;]]></description>
			<content:encoded><![CDATA[<p>Autofac 2.5 is now available on the <a href='http://autofac.org'>project site</a> and via <a href='http://nuget.org'>NuGet</a>. The new version includes a range of great contributions.</p>
<p>After incubation as an <a href='http://www.kowitz.net/autofac-on-wp7'>external project</a>, <a href='http://www.microsoft.com/windowsphone'>Windows Phone 7</a> now joins ranks of officially-supported targets (just install the <code class="codecolorer text default"><span class="text">Autofac</span></code> package via NuGet and you&#8217;re up and running!) For some tips on getting started see <a href='http://www.kowitz.net/configuring-autofac-for-wp7?utm_source=Silverlight-Zone.com&#038;utm_medium=SilverlightZone&#038;utm_campaign=kunal2383'>Brendan Kowitz&#8217;s notes</a>.</p>
<p>The new release is highly-compatible with Autofac 2.4 (best used with the VS2010 compiler when targeting .NET 3.5.)</p>
<p>Included changes are:</p>
<ul>
<li>Issue 329 &#8211; types are filtered by compatibilty before invoking key mapping functions when scanning assemblies</li>
<li><code class="codecolorer text default"><span class="text">RegisterAssemblyTypes(...).WithMetadataFrom&lt;T&gt;()</span></code> simplifies extraction of metadata from attribute properties</li>
<li><code class="codecolorer text default"><span class="text">Module.ThisAssembly</span></code> simplifies implementation of modules that scan their own assembly</li>
<li>Issue 333 &#8211; enable <code class="codecolorer text default"><span class="text">RegisterAssemblyTypes(...).PreserveExistingDefaults()</span></code></li>
<li>Windows Phone 7 and 7.1 support</li>
<li>Issue 312 &#8211; allow <code class="codecolorer text default"><span class="text">ContainerBuilder.Update()</span></code> on the <code class="codecolorer text default"><span class="text">ComponentRegistry</span></code> of any<br />
<code class="codecolorer text default"><span class="text">ILifetimeScope</span></code> without affecting the parent scope</li>
<li>Issue 327 &#8211; allow autowiring of enum properties</li>
<li>Issue 319 &#8211; support list and dictionary literals in XML configuration</li>
<li>Issue 330 &#8211; corrections to generic type constraint checking where the constraint type is an interface</li>
<li>Issue 331 &#8211; fix build warnings and runtime issues using Moq integration</li>
<li>Introduced <code class="codecolorer text default"><span class="text">ContainerBuildOptions</span></code> to control invocation of <code class="codecolorer text default"><span class="text">IStartable.Start()</span></code> under unit tests</li>
<li><code class="codecolorer text default"><span class="text">Container.Empty</span></code> is now a property rather than a field (protection from inadvertent updates</li>
<li>Removed broken/obsolete examples from source tree (better examples are available elsewhere online)</li>
<li>Host configuration features for <code class="codecolorer text default"><span class="text">AutofacHostFactory</span></code> in WCF integration</li>
<li><code class="codecolorer text default"><span class="text">ComponentRegistry.Register()</span></code> is now safe for use under multiple threads</li>
<li>Issue 227 &#8211; <strong>breaking change</strong> additional options (and enum rather than boolean parameter) for <code class="codecolorer text default"><span class="text">PropertiesAutowired()</span></code></li>
<li>Additional web abstractions are now registered by the MVC3 <code class="codecolorer text default"><span class="text">AutofacWebTypesModule</span></code></li>
<li>Issue 311 &#8211; fixed potential lifetime issues when injecting into MVC filter attributes</li>
<li>Tightened up behavior when correct constructor to use under reflection activator is ambiguous (now throws rather than choosing nondeterministically)</li>
<li>Issue 309 &#8211; fixed some issues in <code class="codecolorer text default"><span class="text">TypeExtensions.IsClosedTypeOf()</span></code></li>
<li>Improved exception messages</li>
</ul>
<p>Many thanks to the <a href='http://code.google.com/p/autofac/people/list'>Autofac project team</a> and collaborators across the web for making this release happen!</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/07/autofac-2-5-released/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Designing a Short Course on IoC: Day 5</title>
		<link>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-5/</link>
		<comments>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-5/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 23:09:01 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=309</guid>
		<description><![CDATA[The last of this curious series of journal entries today. As I mentioned previously, today is going to be about finalising the end-to-end flow of topics. I think the first session &#8211; Fundamentals &#8211; is finished. I&#8217;m really excited and even a little nervous about putting together a new container on the fly! As a&#8230;]]></description>
			<content:encoded><![CDATA[<p>The last of this curious series of journal entries today. As I mentioned <a href='http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-4/'>previously</a>, today is going to be about finalising the end-to-end flow of topics.</p>
<p>I think the first session &#8211; Fundamentals &#8211; is finished. I&#8217;m really excited and even a little nervous about putting together a new container on the fly! As a way of bedding down the terminology, mechanics and challenges, I think it is going to be great.</p>
<p>The layout for the remainder of the day still needs work, so I&#8217;d better get stuck into it! Those who&#8217;ve already signed up, I&#8217;ll see you soon &#8211; if you haven&#8217;t put your name down yet for either <a href='http://readify.net/our-events?event-id=62A62934-5215-43FB-9EC4-7F3BF6E058CD'>Brisbane</a>, <a href='http://readify.net/our-events?event-id=9DC9D217-CD23-4A11-90ED-1727E99C1018'>Sydney</a> or <a href='http://readify.net/our-events?event-id=37574063-A9C0-41C9-A4C7-2A6ED6D82DB0'>Melbourne</a>, this is probably the last reminder you&#8217;ll get from me.</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-5/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Designing a Short Course on IoC: Day 4</title>
		<link>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-4/</link>
		<comments>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-4/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 23:33:52 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=304</guid>
		<description><![CDATA[A brief update today. Yesterday I think I covered everything I need to as far as demo app material goes, but tidying up, styling and (egads!) unit testing will have to wait for a rainy day. I spent a fair bit of time yesterday looking at how I can use Whitebox to give an x-ray&#8230;]]></description>
			<content:encoded><![CDATA[<p>A brief update today. <a href='http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-3/'>Yesterday</a> I think I covered everything I need to as far as demo app material goes, but tidying up, styling and (egads!) unit testing will have to wait for a rainy day.</p>
<p>I spent a fair bit of time yesterday looking at how I can use <a href='http://whitebox.googlecode.com'>Whitebox</a> to give an x-ray view of the composition process as the application is built. The information it provides is great &#8211; often revealing little issues that would otherwise go unnoticed &#8211; but the usability leaves me deeply unsatisfied. Still, it <em>is</em> a start, and by chipping away at it things are improving. Just having a simple view of component details is an improvement:</p>
<p><a href="http://nblumhardt.com/wp-content/uploads/2011/03/Capture.png"><img src="http://nblumhardt.com/wp-content/uploads/2011/03/Capture.png" alt="Whitebox component detail view" title="Component Detail" width="493" height="216" class="aligncenter size-full wp-image-306" /></a></p>
<p>Today I&#8217;m concentrating on the flow of the day. I still have some questions to answer around the introductory session &#8211; how theoretical do we want to get? Does it make sense to examine the problems of composition in OO languages, or can we take that as a given for people interested in learning more about IoC? My tendency in the past would have been to go into depth about this, but by starting with &#8220;you&#8217;re going to use IoC &#8211; here&#8217;s how to do it&#8221; I think the practical side of the Dev Day will be emphasised.</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-4/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Designing a Short Course on IoC: Day 3</title>
		<link>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-3/</link>
		<comments>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-3/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 23:59:33 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=300</guid>
		<description><![CDATA[Is it just me, or am I slowing down? Yesterday was a busy day of programming, but there&#8217;s still a long way to go before this application is going to cut the mustard as an example for the course. In the end, I went with the idea of a timesheeting application. Simple material keeps out&#8230;]]></description>
			<content:encoded><![CDATA[<p>Is it just me, or am I slowing down? <a href='http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-2/'>Yesterday</a> was a busy day of programming, but there&#8217;s still a <em>long</em> way to go before this application is going to cut the mustard as an example for the course.</p>
<p>In the end, I went with the idea of a timesheeting application. Simple material keeps out of the way, and to be honest, there is so little logic or fancy presentation in this app that it could be changed from timesheets to another example in a relatively short space of time if need be.</p>
<p>Up and running, we have:</p>
<ul>
<li>A basic MVC3 app layout</li>
<li>IoC set up to create controllers</li>
<li>Data access with <a href='http://nhibernate.org'>NHibernate</a></li>
<li>Transaction management integrated with MVC</li>
<li>Logging with the venerable <a href='http://logging.apache.org/log4net/index.html'>log4net</a></li>
<li>A skeleton for &#8216;pick-me-up&#8217; domain events</li>
</ul>
<p>It is the last item that I&#8217;ll be working on in depth today. <em>&#8216;Pick-me-up&#8217; domain events</em> integrate domain models with external services in a way that plays better with IoC than the thread-static <code class="codecolorer text default"><span class="text">DomainEvents.Raise()</span></code> pattern commonly seen elsewhere.</p>
<p>Dispatching events to handlers is also a good example of the &#8216;generic handler&#8217; pattern that&#8217;s very widely used, and registering handlers will provide some further examples for convention-based/scanning registration.</p>
<p>To complete the day I&#8217;m aiming to polish up the last details of the basic MVC site (for example, error handling) and bed down an example of processing work in a background process to use in the &#8220;Resources and Units of Work&#8221; session. That leaves tomorrow and Friday for more detailed work on slides, some code samples for the &#8220;Containers&#8221; session, and some reworking of the example to fit into the flow of the course.</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-3/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Designing a Short Course on IoC: Day 2</title>
		<link>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-2/</link>
		<comments>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-2/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 00:08:40 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=294</guid>
		<description><![CDATA[So, yesterday, a lot of thinking. Today it&#8217;s time to start fleshing out some of the things we&#8217;ll need. The course is going to be split into four sections, to match the natural division of the day by morning tea, lunch and afternoon tea: Fundamentals Effective IoC Resources and Units of Work Containers and Tooling&#8230;]]></description>
			<content:encoded><![CDATA[<p>So, <a href='http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-1/'>yesterday</a>, a lot of thinking. Today it&#8217;s time to start fleshing out some of the things we&#8217;ll need.</p>
<p>The course is going to be split into four sections, to match the natural division of the day by morning tea, lunch and afternoon tea:</p>
<ol>
<li>Fundamentals</li>
<li>Effective IoC</li>
<li>Resources and Units of Work</li>
<li>Containers and Tooling</li>
</ol>
<h3>Session 1: Fundamentals</h3>
<p>First up, we&#8217;ll set the theme of the day with some collaborative development. To introduce the vocabulary and concepts of IoC, we&#8217;ll write a simple IoC container in C# and integrate it into an ASP.NET MVC application. There are plenty of interesting design issues along the way that we&#8217;ll come back to in our discussion of containers and tooling.</p>
<h3>Session 2: Effective IoC</h3>
<p>The second session will introduce a &#8216;real&#8217; IoC container. The focus will be on techniques and features that allow IoC to support large, complex applications in the real world. We&#8217;ll touch on all of the typical components of MVC web applications as we migrate from the simple container we built ourselves, but we&#8217;ll pay special attention to the integration between IoC and domain models because of the challenges and opportunities they present.</p>
<h3>Session 3: Resources and Units of Work</h3>
<p><a href='http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/'>Lifetime</a>, AKA &#8220;resource management&#8221; can be the toughest aspect of IoC to master. We&#8217;ll take an excursion outside of the comfort of the web tier, to develop a thorough understanding of the issues involved and their solutions.</p>
<p>Although it is far from being ready for prime time, <a href='http://whitebox.googlecode.com'>Whitebox</a> will be a great way to explore the runtime behaviour of lifetime scenarios, so sometime over the coming week I&#8217;ll look at filling remaining gaps there.</p>
<h3>Session 4: Containers and Tooling</h3>
<p>To round out the day, we&#8217;ll use the last session to take a leisurely tour of the sights, sounds and smells of the .NET IoC ecosystem. Choosing an IoC container can be tricky business, especially when the easiest metrics to grasp, for example throughput performance, are often misleading or irrelevant. In addition to looking at some of the popular offerings and their relative strengths, I think this is where a discussion of MEF and its role will fit in nicely.</p>
<p>Session 4 will also give us an opportunity to examine debugging and diagnostics issues.</p>
<h2>Today</h2>
<p>So, what do you think?</p>
<p>Today&#8217;s focus for me will be to take a first cut at building the example application. I&#8217;m going to leave the &#8216;simple container&#8217; design task for the event, so that we can truly do it on the fly! I want the day to be heavy on code and light on slides, so dressing up a slide deck with some guiding material will wait for later in the week.</p>
<p>Choosing what kind of application to build is tricky. I want attendees to be able to take something away, ideally a sample that isn&#8217;t too far from production readiness. In that respect, simpler will be better, though it can be hard to get enough breadth out of something like a &#8216;to-do&#8217; or &#8216;timesheeting&#8217; application. There&#8217;s some high-quality code on the web that might be reused for this purpose (e.g. <a href='http://funnelweblog.com'>FunnelWeb</a>) so building something that mimics an existing open source application has advantages.</p>
<p>I&#8217;ll update you tomorrow on where things land.</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Designing a Short Course on IoC: Day 1</title>
		<link>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-1/</link>
		<comments>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-1/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 23:09:50 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=290</guid>
		<description><![CDATA[Today&#8217;s the start of a really exciting week for me! I&#8217;ve been working with Inversion of Control (IoC) Containers and related technologies since picking up Castle Windsor in 2006, actively developed Autofac for much of that time, and helped shape the first release of the Managed Extensibility Framework. In that period IoC has grown and&#8230;]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s the start of a really exciting week for me!</p>
<p>I&#8217;ve been working with Inversion of Control (IoC) Containers and related technologies since picking up <a href='http://castleproject.org'>Castle Windsor</a> in 2006, actively developed <a href='http://autofac.org'>Autofac</a> for much of that time, and helped shape the first release of the <a href='http://mef.codeplex.com'>Managed Extensibility Framework</a>. In that period IoC has grown and truly blossomed in the .NET world: from its &#8220;enterprise Java&#8221; <a href='http://avalon.apache.org'>roots</a> we&#8217;ve collectively created something that plays to the unique strengths of .NET and C#. Rather than being viewed as an esoteric fringe technology, as it was just a few years ago, IoC is firmly in the .NET mainstream and is increasingly being baked into the platform itself.</p>
<p>Along the way there have been many difficult questions posed, and I&#8217;ve had to ask and answer my share. It can be easy to go wrong with IoC &#8211; remember the &#8220;<a href='http://ayende.com/Blog/archive/2008/03/09/ALT.Net-Logo.aspx'>sharp tools</a>&#8221; analogy of the ALT.NET movement? &#8211; especially when finding the right approach to IoC in a new situation can mean finding several wrong ways first!</p>
<p>Last year at <a href='http://www.msteched.com/2010/Australia/DEV426'>TechEd Australia</a> I presented a breakout session on IoC in .NET. Though the feedback I received was positive, I was left feeling that an hour was too little time to get many of the concepts across in enough depth. So, this year courtesy of <a href='http://readify.net'>Readify</a> I&#8217;m going to be presenting a short course on <strong>IoC from the ground, up</strong>.</p>
<p>The course will be a full day, with dates in <em>May, 2011</em> set for:</p>
<ul>
<li><a href='http://readify.net/our-events?event-id=62A62934-5215-43FB-9EC4-7F3BF6E058CD'>Brisbane</a>,</li>
<li><a href='http://readify.net/our-events?event-id=9DC9D217-CD23-4A11-90ED-1727E99C1018'>Sydney</a> and</li>
<li><a href='http://readify.net/our-events?event-id=37574063-A9C0-41C9-A4C7-2A6ED6D82DB0'>Melbourne</a>.</li>
</ul>
<p>The unifying theme will be <a href='http://asp.net/mvc'>ASP.NET MVC</a>, but don&#8217;t be discouraged if this is not your primary platform. Much of what we cover will be independent of MVC and even of web programming in general. If you&#8217;re unfamiliar with ASP.NET MVC then it might help to brush up on that area if you want to keep up with some of the examples.</p>
<p>In terms of level of technical difficulty, I hope there will be something for everyone. You&#8217;ll get the most out of the day if you&#8217;re a confident .NET developer with beginner-to-intermediate experience with IoC, or if you&#8217;re an experienced user of IoC looking for broader and deeper perspectives on its use.</p>
<p>This week I&#8217;m preparing material for the course, and while I have a fair idea of the ground to cover, I&#8217;m interested in your ideas. I&#8217;ll be posting a progress update each day to keep you informed of where things are heading. I hope in the process I can convince you to come along, and bring your team!</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/03/designing-a-short-course-on-ioc-day-1/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Autofac 2.4.5 Release</title>
		<link>http://nblumhardt.com/2011/03/autofac-2-4-5-release/</link>
		<comments>http://nblumhardt.com/2011/03/autofac-2-4-5-release/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 00:17:09 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=284</guid>
		<description><![CDATA[More than a month has passed since the last patch release of Autofac 2.4, and enough has changed in trunk to warrant a new one. You can download Autofac 2.4.5 from the project site, or preferably, update your NuGet packages within Visual Studio. In this release you&#8217;ll find: Several bug fixes and improved exception messages&#8230;]]></description>
			<content:encoded><![CDATA[<p>More than a month has passed since the last patch release of Autofac 2.4, and enough has changed in trunk to warrant a new one. You can download Autofac 2.4.5 from <a href="http://autofac.org">the project site</a>, or preferably, update your <a href="http://nuget.org">NuGet</a> packages within Visual Studio.</p>
<p>In this release you&#8217;ll find:</p>
<ul>
<li>Several bug fixes and improved exception messages</li>
<li><a href="http://www.paraesthesia.com/">Travis</a> and <a href="http://alexmg.com">Alex</a> have been busy making the Multi-tenant contrib package work better with the new ASP.NET MVC3 integration</li>
<li>The awkward but very useful <code class="codecolorer text default"><span class="text">IContainerAwareComponent</span></code> introduced in 2.4 has been deprecated and morphed into a much friendlier and more useful <a href="http://code.google.com/p/autofac/wiki/Startable">Startable</a> implementation</li>
<li>Autofac now consistently throws <code class="codecolorer text default"><span class="text">DependencyResolutionException</span></code> (or a subclass) whenever fatal errors occur during composition</li>
</ul>
<p>Please feel free to drop in and share your experiences on the <a href="https://groups.google.com/forum/#!forum/autofac">discussion forum</a>. For help with using Autofac, including new features, the preferred medium is <a href="http://stackoverflow.com/questions/tagged/autofac">Stack Overflow</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/03/autofac-2-4-5-release/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Autofac 2.4 is here – come and “NuGet” it!</title>
		<link>http://nblumhardt.com/2011/01/autofac-2-4-is-here-%e2%80%93-come-and-%e2%80%9cnuget%e2%80%9d-it/</link>
		<comments>http://nblumhardt.com/2011/01/autofac-2-4-is-here-%e2%80%93-come-and-%e2%80%9cnuget%e2%80%9d-it/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 23:25:27 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Autofac]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=271</guid>
		<description><![CDATA[The latest release of the Autofac IoC container is now available on the project site and via NuGet. ASP.NET MVC Integration Changes The best thing in the new release, and possibly since sliced bread, is the new Autofac ASP.NET MVC integration. Gone are special interfaces on HttpApplication, gone are the Web.config file edits, static properties&#8230;]]></description>
			<content:encoded><![CDATA[<p>The latest release of the Autofac IoC container is now available on the <a href='http://autofac.org'>project site</a> and via <a href='http://nuget.org'>NuGet</a>.</p>
<h3>ASP.NET MVC Integration Changes</h3>
<p>The best thing in the new release, and possibly since sliced bread, is the new Autofac ASP.NET MVC integration. Gone are special interfaces on <code class="codecolorer text default"><span class="text">HttpApplication</span></code>, gone are the <code class="codecolorer text default"><span class="text">Web.config</span></code> file edits, static properties in the application class and multiple different extension points to configure. It couldn’t get any simpler than this.</p>
<p>Here’s how you create a new Autofac-enabled ASP.NET MVC3 project:</p>
<h4>1. Create a new MVC3 web application</h4>
<p><a href="http://nblumhardt.com/wp-content/uploads/2011/01/Step1.png"><img src="http://nblumhardt.com/wp-content/uploads/2011/01/Step1.png" alt="" title="Step1" width="858" height="456" class="aligncenter size-full wp-image-272" /></a></p>
<h4>2. Install the Autofac.Mvc3 Package</h4>
<p><a href="http://nblumhardt.com/wp-content/uploads/2011/01/Step2.png"><img src="http://nblumhardt.com/wp-content/uploads/2011/01/Step2.png" alt="" title="Step2" width="837" height="591" class="aligncenter size-full wp-image-273" /></a></p>
<h4>3. Set up the Container and DependencyResolver </h4>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #6666cc; font-weight: bold;">void</span> Application_Start<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; var builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ContainerBuilder<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; builder<span style="color: #008000;">.</span><span style="color: #0000FF;">RegisterControllers</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>MvcApplication<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Assembly</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; var container <span style="color: #008000;">=</span> builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Build</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; DependencyResolver<span style="color: #008000;">.</span><span style="color: #0000FF;">SetResolver</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> AutofacDependencyResolver<span style="color: #008000;">&#40;</span>container<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #008080; font-style: italic;">// Other MVC setup...</span></div></div>
<h4>That’s it!</h4>
<p>That’s all you need to do to enable dependency injection into your controllers. There’s a lot more you can do with Autofac and ASP.NET MVC3 – I highly recommend checking out some of <a href='http://alexmg.com/category/Autofac.aspx'>Alex’s</a> recent posts on the subject.</p>
<p>The Autofac ASP.NET MVC integration now targets ASP.NET MVC <strong>version 3</strong> exclusively. Don’t worry if you’re unable to move to MVC3 right away, see the “Using Autofac 2.4 with ASP.NET MVC2” below.</p>
<h3>Complete NuGet Packages</h3>
<p>With Autofac 2.4, the recommended way to add Autofac and its sub-features to your applications is to use the <a href='http://nuget.org'>NuGet package manager</a>. You can see some of the available packages in the screen shot at step 2 above. Just search for “Autofac” and you’re away.</p>
<p>In the previous Autofac NuGet package, we included the MEF and WCF integrations by default. To keep clutter away, these are now in their own packages Autofac.Mef and Autofac.Wcf respectively.</p>
<h3>Improved Decorator Support</h3>
<p>The new and improved <a href=' http://nblumhardt.com/2011/01/decorator-support-in-autofac-2-4/'>decorator support</a> makes it much easier to wire up generic decorators with Autofac, and also provides a nice boost when using decorators in other scenarios.</p>
<h3>Removed Older Silverlight Versions from Supported Builds</h3>
<p>To keep the maintenance burden of the project as light as practical, it is occasionally necessary to discontinue ‘official’ support for older framework versions. In Autofac 2.4, the Silverlight 3 configuration is no longer available. Users of Silverlight 3 should continue to run the Autofac 2.3 builds (bug fixes will be provided for these whenever necessary.)</p>
<h3>Events and Interfaces to Support Tracing</h3>
<p>Like all IoC containers, Autofac’s internals can be somewhat opaque to follow at runtime. For the occasions that diagnostics are necessary, Autofac 2.4 supports more events that can be used to trace the operations of the container. As an example, <code class="codecolorer text default"><span class="text">ILifetimeScope</span></code> now supports <code class="codecolorer text default"><span class="text">LifetimeScopeBeginning</span></code>, <code class="codecolorer text default"><span class="text">ResolveOperationBeginning</span></code> and other related extension points.</p>
<p>It is intended that these will be used more by Autofac integration and tooling developers than in general application development.</p>
<h3>Other Release Notes</h3>
<p>The community has been busy as usual, and you’ll find quite a few other enhancements in this release.</p>
<ul>
<li><code class="codecolorer text default"><span class="text">.AsImplementedInterfaces()</span></code> is now supported on non-scanning registrations</li>
<li><code class="codecolorer text default"><span class="text">IDisposable</span></code> is no longer considered a service by <code class="codecolorer text default"><span class="text">.AsImplementedInterfaces()</span></code></li>
<li>Additional eager checks for generic type/service compatibility at registration time</li>
<li>An additional <code class="codecolorer text default"><span class="text">.WithParameter()</span></code> overload has been added, accepting predicate and value accessor like <code class="codecolorer text default"><span class="text">ResolvedParameter</span></code></li>
<li>Extension methods for common predicates on <code class="codecolorer text default"><span class="text">System.Type</span></code> are now public for use with scanning, e.g. <code class="codecolorer text default"><span class="text">Except(t =&gt; t.IsClosedTypeOf(x))</span></code></li>
<li>MVC <code class="codecolorer text default"><span class="text">ExtensibleActionInvoker</span></code> does not inject action method parameters by default</li>
<li><code class="codecolorer text default"><span class="text">ILifetimeScope</span></code> rather than <code class="codecolorer text default"><span class="text">IContainer</span></code> is now accepted by ServiceHostBase (WCF integration)</li>
<li><code class="codecolorer text default"><span class="text">AutofacInstanceContext</span></code> has been made public so that current scope can be retrieved when needed (WCF integration)</li>
<li>Bug fixes and enhancements in AutofacContrib.Multitenant and AutofacContrib.Attributed</li>
<li>Dependencies upgraded e.g. Castle Core and NHibernate</li>
<li>Fixed bug #288 &#8211; resolve all failing in customised lifetime scopes when one component supports multiple interfaces</li>
</ul>
<h3>Using Autofac 2.4 with ASP.NET MVC2</h3>
<p>If you’re  still using ASP.NET MVC2 in your application, the simplest course of action is to continue using the Autofac 2.3 release series and the appropriate integration bundled with that, until you’re able to upgrade wholesale to ASP.NET MVC3.</p>
<p>If you would like to use Autofac 2.4 with ASP.NET MVC, there is an updated Autofac.Mvc2 NuGet package now on the feed. If you’re already using the MVC2 NuGet package, update the package and you should be fine. If not, first remove all <code class="codecolorer text default"><span class="text">Autofac*.dll</span></code> references from your project and then install the Autofac.Mvc2 package using the “Add Library Reference” dialog.</p>
<p><strong>Edit:</strong> You need to add assembly binding redirects in order for the MVC2 package to work. The appropriate redirects are specified below (you may need to update them with the current Autofac version number) or you can use the commands <a href='http://blog.davidebbo.com/2011/01/nuget-versioning-part-3-unification-via.html'>bundled with NuGet</a>.</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #008000;">&lt;</span>runtime<span style="color: #008000;">&gt;</span><br />
&nbsp; <span style="color: #008000;">&lt;</span>assemblyBinding xmlns<span style="color: #008000;">=</span><span style="color: #666666;">&quot;urn:schemas-microsoft-com:asm.v1&quot;</span><span style="color: #008000;">&gt;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&lt;</span>dependentAssembly<span style="color: #008000;">&gt;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #008000;">&lt;</span>assemblyIdentity name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Autofac&quot;</span> publicKeyToken<span style="color: #008000;">=</span><span style="color: #666666;">&quot;17863af14b0044da&quot;</span> <span style="color: #008000;">/&gt;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #008000;">&lt;</span>bindingRedirect oldVersion<span style="color: #008000;">=</span><span style="color: #666666;">&quot;2.3.2.632&quot;</span> newVersion<span style="color: #008000;">=</span><span style="color: #666666;">&quot;2.4.3.700&quot;</span> <span style="color: #008000;">/&gt;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&lt;/</span>dependentAssembly<span style="color: #008000;">&gt;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&lt;</span>dependentAssembly<span style="color: #008000;">&gt;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #008000;">&lt;</span>assemblyIdentity name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Autofac.Integration.Web&quot;</span> publicKeyToken<span style="color: #008000;">=</span><span style="color: #666666;">&quot;17863af14b0044da&quot;</span> <span style="color: #008000;">/&gt;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #008000;">&lt;</span>bindingRedirect oldVersion<span style="color: #008000;">=</span><span style="color: #666666;">&quot;2.3.2.632&quot;</span> newVersion<span style="color: #008000;">=</span><span style="color: #666666;">&quot;2.4.3.700&quot;</span> <span style="color: #008000;">/&gt;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&lt;/</span>dependentAssembly<span style="color: #008000;">&gt;</span><br />
&nbsp; <span style="color: #008000;">&lt;/</span>assemblyBinding<span style="color: #008000;">&gt;</span><br />
<span style="color: #008000;">&lt;/</span>runtime<span style="color: #008000;">&gt;</span></div></div>
<h3>Summing Up</h3>
<p>I hope that with this release, Autofac is now easier to get and set up than ever before. It has once again been a team effort – thanks especially to the <a href=' http://code.google.com/p/autofac/people/list'>contributors</a> and everyone who has submitted issue reports or patches.</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/01/autofac-2-4-is-here-%e2%80%93-come-and-%e2%80%9cnuget%e2%80%9d-it/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>An Autofac Lifetime Primer</title>
		<link>http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/</link>
		<comments>http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/#comments</comments>
		<pubDate>Fri, 21 Jan 2011 03:04:38 +0000</pubDate>
		<dc:creator>Nicholas Blumhardt</dc:creator>
				<category><![CDATA[Autofac]]></category>

		<guid isPermaLink="false">http://nblumhardt.com/?p=257</guid>
		<description><![CDATA[Or, “Avoiding Memory Leaks in Managed Composition” Understanding lifetime can be pretty tough when you’re new to IoC. Even long-time users express vague fears and misgivings when it comes to this subject, and disconcerting issues – components not being disposed, steadily climbing memory usage or an OutOfMemoryException – have bitten many of us at one&#8230;]]></description>
			<content:encoded><![CDATA[<p><em>Or, “Avoiding Memory Leaks in Managed Composition”</em></p>
<p>Understanding lifetime can be pretty tough when you’re new to IoC. Even long-time users express vague fears and misgivings when it comes to this subject, and disconcerting issues – components not being disposed, steadily climbing memory usage or an <code class="codecolorer text default"><span class="text">OutOfMemoryException</span></code> – have bitten many of us at <a href='http://matthamilton.net/autofac-and-transient-objects'>one time</a> or <a href='http://davybrion.com/blog/2010/02/avoiding-memory-leaks-with-nservicebus-and-your-own-castle-windsor-instance/'>another</a>.</p>
<p>Avoiding lifetime issues when using an IoC container is generally straightforward, but doing so successfully is more a question of application design rather than just container API usage. There’s lots of good advice out there, but very little of it tells the complete story from beginning to end. I’ve attempted to do that with this rather long article, and hope that with a bit of feedback from you it can be shaped into a useful reference.</p>
<p>This article is about Autofac, but the broad issues are universal – even if you’re not an Autofac user, chances are there’s something to learn about your container of choice.</p>
<h3>What Leaks?</h3>
<p>Let’s begin with the issue that in all likelihood brought you here. <em>Tracking</em> containers like Autofac hold references to the disposable components they create.</p>
<p>By <em>disposable</em> we mean any component that implements the BCL’s <code class="codecolorer text default"><span class="text">IDisposable</span></code> interface (or is configured with an <code class="codecolorer text default"><span class="text">OnRelease()</span></code> <a href='http://code.google.com/p/autofac/wiki/OnActivatingActivated'>action</a>):</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">interface</span> IMyResource <span style="color: #008000;">&#123;</span> … <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #6666cc; font-weight: bold;">class</span> MyResource <span style="color: #008000;">:</span> IMyResource, IDisposable <span style="color: #008000;">&#123;</span> … <span style="color: #008000;">&#125;</span></div></div>
<p>When an instance of <code class="codecolorer text default"><span class="text">MyResource</span></code> is created in an Autofac container, the container will hold a reference to it even when it is no longer being used by the rest of the program. This means that the garbage collector will be unable to reclaim the memory held by that component, so the following program will eventually exhaust all available memory and crash:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">var builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ContainerBuilder<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
builder<span style="color: #008000;">.</span><span style="color: #0000FF;">RegisterType</span><span style="color: #008000;">&lt;</span>MyResource<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">As</span><span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var container <span style="color: #008000;">=</span> builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Build</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; var r <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// Out of memory!</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>This is a far cry from typical CLR behaviour, which is one more reason why it is good to get away from thinking about an IoC container as a replacement for <code class="codecolorer text default"><span class="text">new</span></code>. If we’d just created <code class="codecolorer text default"><span class="text">MyResource</span></code> directly in the loop, there wouldn’t be any problem at all:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; var r <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MyResource<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// Fine, feed the GC</span></div></div>
<h4>Transitive Dependencies</h4>
<p>Looking at the code above you might be tempted to think that the problem only surfaces when disposable components are resolved directly from the container. That’s not really the case &#8211; <em>every</em> disposable component created by the container is tracked, even those created indirectly to satisfy dependencies.</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">interface</span> IMyService <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #6666cc; font-weight: bold;">class</span> MyComponent <span style="color: #008000;">:</span> IMyService<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #008080; font-style: italic;">// Dependency on a service provided by a disposable component</span><br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> MyComponent<span style="color: #008000;">&#40;</span>IMyResource resource<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> … <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>If a second component is resolved that depends on a service provided by a disposable component, the memory leak still occurs:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008080; font-style: italic;">// Still holds instances of MyResource</span><br />
&nbsp; &nbsp; var s <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IMyService<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></div></div>
<h4>Results Returned from Delegate Factories</h4>
<p>Rather than calling <code class="codecolorer text default"><span class="text">Resolve()</span></code> directly on an <code class="codecolorer text default"><span class="text">IContainer</span></code> we might instead take a dependency on an Autofac delegate factory type like <code class="codecolorer text default"><span class="text">Func&lt;T&gt;</span></code>:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">interface</span> IMyService2<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #6666cc; font-weight: bold;">void</span> Go<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #6666cc; font-weight: bold;">class</span> MyComponent2 <span style="color: #008000;">:</span> IMyService2<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; Func<span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;</span> _resourceFactory<span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> MyComponent<span style="color: #008000;">&#40;</span>Func<span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;</span> resourceFactory<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; _resourceFactory <span style="color: #008000;">=</span> resourceFactory<span style="color: #008000;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Go<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var r <span style="color: #008000;">=</span> _resourceFactory<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// Still out of memory.</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Now in the main loop we only resolve one component instance and call the <code class="codecolorer text default"><span class="text">Go()</span></code> method.</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var container <span style="color: #008000;">=</span> builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Build</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; var s <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IMyService2<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; s<span style="color: #008000;">.</span><span style="color: #0000FF;">Go</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Even though we’ve only called the container once directly, the leak is still there.</p>
<h3>Why does Autofac behave this way?</h3>
<p>It might seem that there are several traps here, though there’s really only one – and it is worth reiterating:</p>
<p><strong>Autofac will track every disposable component instance that it creates, no matter how that instance is requested.</strong></p>
<p>This isn’t, of course, the end of the road. Autofac is very carefully designed to make resource management easier than programming without a container. Notice I slipped in the word <em>resource</em> there? The ‘memory leaks’ we’re talking about are a result of preventing another kind of ‘leak’ – the resources that are managed through <code class="codecolorer text default"><span class="text">IDisposable</span></code>.</p>
<h4>What are Resources?</h4>
<p>Traditionally, a <em>resource</em> might be defined as anything with finite capacity that must be shared between its users.</p>
<p>In the context of components in an IoC container, a resource is anything with <em>acquisition</em> and <em>release</em> phases in its lifecycle. Many low-level examples exist, such as components that rely on items from the list below, but it is also very common to find high-level application constructs with similar semantics.</p>
<ul>
<li>Locks (e.g. Monitor.Enter() and Monitor.Exit())</li>
<li>Transactions (Begin and Commit/Abort)</li>
<li>Event subscriptions (+= and -=)</li>
<li>Timers (Start and Dispose)</li>
<li>Machine resources like sockets and files (usually Open/Create and Close)</li>
<li>Waiting worker threads (Create and Signal)</li>
</ul>
<p>In .NET there’s a standard way to represent resource semantics on a component by implementing <code class="codecolorer text default"><span class="text">IDisposable</span></code>. When such a component is no longer required, the <code class="codecolorer text default"><span class="text">Dispose()</span></code> method must be called to complete the ‘release’ phase.</p>
<h5>Not Calling Dispose() is most often a Bug</h5>
<p>You can read some interesting discussions via <a href='http://blogs.msdn.com/b/kimhamil/archive/2008/11/05/when-to-call-dispose.aspx'>Kim Hamilton’s</a> and <a href='http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae'>Joe Duffy’s</a> articles on the topic of when <code class="codecolorer text default"><span class="text">Dispose()</span></code> must be called.</p>
<p>There’s a fairly strong consensus that more often than not, failing to call <code class="codecolorer text default"><span class="text">Dispose()</span></code> will lead to a bug, regardless of whether or not the resource in question is protected by a finalizer (or <code class="codecolorer text default"><span class="text">SafeHandle</span></code>).</p>
<p>What is less clear is how applications and APIs should be structured so that <code class="codecolorer text default"><span class="text">Dispose()</span></code> can be called reliably and at the correct time.</p>
<h4>IDisposable and Ownership</h4>
<p>Before IoC (assuming you use it now) there were probably two approaches you could apply to calling <code class="codecolorer text default"><span class="text">Dispose()</span></code>:</p>
<ol>
<li>The C# <code class="codecolorer text default"><span class="text">using</span></code> statement</li>
<li>Ad-hoc</li>
</ol>
<p><code class="codecolorer text default"><span class="text">IDisposable</span></code> and <code class="codecolorer text default"><span class="text">using</span></code> are a match made in heaven, but they only apply when a resource’s lifetime is within a single method call.</p>
<p>For everything else, you need to find a strategy to ensure resources are disposed when they’re no longer required. The most widely-attempted one is based around the idea that whatever object <em>acquires</em> the resource should also <em>release</em> it. I pejoratively call it “ad-hoc” because it doesn’t work consistently. Eventually you’ll come up against one (and likely more) of the following issues:</p>
<p><strong>Sharing</strong>: When multiple independent components share a resource, it is very hard to figure out when none of them requires it any more. Either a third party will have to know about all of the potential users of the resource, or the users will have to collaborate. Either way, things get hard fast.</p>
<p><strong>Cascading Changes</strong>: Let’s say we have three components – <code class="codecolorer text default"><span class="text">A</span></code> uses <code class="codecolorer text default"><span class="text">B</span></code> which uses <code class="codecolorer text default"><span class="text">C</span></code>. If no resources are involved, then no thought needs to be given to how resource ownership or release works. But, if the application changes so that <code class="codecolorer text default"><span class="text">C</span></code> must now own a disposable resource, then both <code class="codecolorer text default"><span class="text">A</span></code> and <code class="codecolorer text default"><span class="text">B</span></code> will probably have to change to signal appropriately (via disposal) when that resource is no longer needed. The more components involved, the nastier this one is to unravel.</p>
<p><strong>Contract vs. Implementation</strong>: In .NET we’re encouraged to program to a contract, not an implementation. Well-designed APIs don’t usually give details of the implementation type, for example an Abstract Factory could be employed to create caches of different sizes:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF; font-weight: bold;">public</span> ICache CreateCache<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> maximumByteSize<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> &nbsp;<span style="color: #008080; font-style: italic;">// Abstract Factory</span><br />
<br />
<span style="color: #6666cc; font-weight: bold;">interface</span> ICache <span style="color: #008080; font-style: italic;">// : IDisposable?</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #6666cc; font-weight: bold;">void</span> Add<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> key, <span style="color: #6666cc; font-weight: bold;">object</span> value, TimeSpan ttl<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; <span style="color: #6666cc; font-weight: bold;">bool</span> TryLookup<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> key, <span style="color: #0600FF; font-weight: bold;">out</span> <span style="color: #6666cc; font-weight: bold;">object</span> value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>The initial implementation may return only <code class="codecolorer text default"><span class="text">MemoryCache</span></code> objects, that have no resource management requirements. However, because we may in future create a <code class="codecolorer text default"><span class="text">FileCache</span></code> implementation, does that mean that <code class="codecolorer text default"><span class="text">ICache</span></code> should be disposable?</p>
<p>The root of the problem here is that for <em>any</em> contract, it is conceivable that there will one day be an implementation that is disposable.</p>
<p>This particular problem is exacerbated by loosely-coupled systems like those built with IoC. Since components only know about each other through contracts (services) and never their implementation types, there really isn’t any way for one component to determine whether it should try to dispose another.</p>
<h4>IoC to the Rescue!</h4>
<p>There is a viable solution out there. As you can guess, a) <strong>in typical enterprise and web applications</strong> and b) <strong>at a certain level of granularity</strong> IoC containers provide a good solution to the resource management problem.</p>
<p>To do this, they need to take ownership of the disposable components that they create.</p>
<p>But this is only part of the story – they also need to be told about the units of work that the application performs. This is how the container will know to dispose components and release references, avoiding the memory leak problems that will otherwise occur.</p>
<p><em><strong>Why not have the container use WeakReference just to be safe?</strong> A solution that relies on <code class="codecolorer text default"><span class="text">WeakReference</span></code> is afflicted by the same problems as not calling <code class="codecolorer text default"><span class="text">Dispose()</span></code> at all. Allowing components to be garbage collected before the enclosing unit of work is complete can lead to a whole class of subtle load- and environment-dependent bugs. Many higher-level resources are also unable to be properly released within a finalizer.</em></p>
<h3>Units of Work</h3>
<p>As they run, enterprise and web applications tend to perform tasks with a defined beginning and end. These tasks might be things like responding to a web request, handling an incoming message, or running a batch process over some data.</p>
<p>These are tasks in the abstract sense – not to be confused with something like <code class="codecolorer text default"><span class="text">Task&lt;T&gt;</span></code> or any of the asynchronous programming constructs. To make this clearer, we’ll co-opt the term ‘unit of work’ to describe this kind of task.</p>
<p>Determining where units of work begin and end is the key to using Autofac effectively in an application.</p>
<h3>Lifetime Scopes: Implementing Units of Work with Autofac</h3>
<p>Autofac caters to units of work through <em>lifetime scopes</em>. A lifetime scope (<code class="codecolorer text default"><span class="text">ILifetimeScope</span></code>) is just what it sounds like – a scope at the completion of which, the lifetime of a set of related components will end.</p>
<p>Component instances that are resolved during the processing of a unit of work get associated with a lifetime scope. By tracking instantiation order and ensuring that dependencies can only be satisfied by components in the same or a longer-lived lifetime scope, Autofac can take responsibility for disposal when the lifetime scope ends.</p>
<p>Going back to our original trivial example, the leak we observed can be eliminated by creating and disposing a new lifetime scope each time we go through the loop:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #008080; font-style: italic;">// var container = …</span><br />
<span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var lifetimeScope <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; var r <span style="color: #008000;">=</span> lifetimeScope<span style="color: #008000;">.</span><span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008080; font-style: italic;">// r, all of its dependencies and any other components</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008080; font-style: italic;">// created indirectly will be released here</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>This is all it takes to avoid memory and resources leaks with Autofac.</p>
<p><strong>Don’t resolve from the root container. Always resolve from and then release a lifetime scope.</strong></p>
<p>Lifetime scopes are extremely flexible and can be applied to a huge range of scenarios. There are a few handy things to know that might not be immediately obvious.</p>
<h4>Lifetime Scopes can Exist Simultaneously</h4>
<p>Many lifetime scopes can exist simultaneously on the same container.  This is how incoming HTTP requests are handled in the Autofac ASP.NET integration, for example. Each request causes the creation of a new lifetime scope for handling it; this gets disposed at the end of the request.</p>
<p><a href="http://nblumhardt.com/wp-content/uploads/2011/01/Concurrent-Scopes.png"><img src="http://nblumhardt.com/wp-content/uploads/2011/01/Concurrent-Scopes.png" alt="" title="Concurrent Scopes" width="381" height="219" class="aligncenter size-full wp-image-258" /></a> </p>
<p>Note that we call the root of the lifetime scope hierarchy the ‘Application’ scope, because it will live for the duration of an application run.</p>
<h4>Lifetime Scopes can be Nested</h4>
<p>The container itself is the root lifetime scope in an Autofac application. When a lifetime scope is created from it, this sets up a parent-child relationship between the nested scope and the container.</p>
<p>When dependencies are resolved, Autofac first attempts to satisfy the dependency with a component instance in the scope in which the request was made.  In the diagram below, this means that the dependency on an NHibernate session is satisfied within the scope of the HTTP request and the session will therefore be disposed when the HTTP request scope ends.</p>
<p><a href="http://nblumhardt.com/wp-content/uploads/2011/01/Dep-res-process.png"><img src="http://nblumhardt.com/wp-content/uploads/2011/01/Dep-res-process.png" alt="" title="Dep res process" width="765" height="373" class="aligncenter size-full wp-image-259" /></a></p>
<p>When the dependency resolution process hits a component that cannot be resolved in the current scope – for example, a component configured as a Singleton using <code class="codecolorer text default"><span class="text">SingleInstance()</span></code>, Autofac looks to the parent scope to see if the dependency can be resolved there.</p>
<p><a href="http://nblumhardt.com/wp-content/uploads/2011/01/Dep-res-process2.png"><img src="http://nblumhardt.com/wp-content/uploads/2011/01/Dep-res-process2.png" alt="" title="Dep res process2" width="725" height="372" class="aligncenter size-full wp-image-260" /></a></p>
<p>When the resolve operation has moved from a child scope to the parent, any further dependencies will be resolved in the parent scope. If the <code class="codecolorer text default"><span class="text">SingleInstance()</span></code> component <code class="codecolorer text default"><span class="text">Log</span></code> depends on <code class="codecolorer text default"><span class="text">LogFile</span></code> then the log file dependency will be associated with the root scope, so that even when the current HTTP request scope ends, the file component will live on with the log that depends on it.</p>
<p>Lifetime scopes can be nested to arbitrary depth:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">var ls1 <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
var ls2 <span style="color: #008000;">=</span> ls1<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #008080; font-style: italic;">// ls1 is a child of the container, ls2 is a child of ls1</span></div></div>
<h4>Sharing is driven by Lifetime Scopes</h4>
<p>At this point in our discussion of lifetime management (you thought we were going to talk about memory leaks but that’s just how I roped you in!) it is worth mentioning the relationship between lifetime scopes and how Autofac implements ‘sharing’.</p>
<p>By default, every time an instance of a component is needed (either requested directly with the <code class="codecolorer text default"><span class="text">Resolve()</span></code> method or as a dependency of another component) Autofac will create a new instance and, if it is disposable, attach it to the current lifetime scope. All IoC containers that I know of support something like this kind of ‘transient lifestyle’ or ‘instance per dependency.’</p>
<p>Also universally supported is ‘singleton’ or ‘single instance’ sharing, in which the same instance is used to satisfy all requests. In Autofac, <code class="codecolorer text default"><span class="text">SingleInstance()</span></code> sharing will associate an instance with the root node in the tree of active lifetime scopes, i.e. the container.</p>
<p>There are two other common sharing modes that are used with Autofac.</p>
<h5>Matching Scope Sharing</h5>
<p>When creating a scope, it is possible to give it a name in the form of a ‘tag’:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #008080; font-style: italic;">// For each session concurrently managed by the application</span><br />
var sessionScope <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;session&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<br />
<span style="color: #008080; font-style: italic;">// For each message received in the session:</span><br />
var messageScope <span style="color: #008000;">=</span> sessionScope<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;message&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
var dispatcher <span style="color: #008000;">=</span> messageScope<span style="color: #008000;">.</span><span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IMessageDispatcher<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
dispatcher<span style="color: #008000;">.</span><span style="color: #0000FF;">Dispatch</span><span style="color: #008000;">&#40;</span>…<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></div></div>
<p>Tags name the levels in the lifetime scope hierarchy, and they can be used when registering components in order to determine how instances are shared.</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">builder<span style="color: #008000;">.</span><span style="color: #0000FF;">RegisterType</span><span style="color: #008000;">&lt;</span>CredentialCache<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">.</span><span style="color: #0000FF;">InstancePerMatchingLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;session&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></div></div>
<p>In this scenario, when processing messages in a session, even though we always <code class="codecolorer text default"><span class="text">Resolve()</span></code> dependencies from the <code class="codecolorer text default"><span class="text">messageScope</span></code>s, all components will share a single <code class="codecolorer text default"><span class="text">CredentialCache</span></code> at the session level.</p>
<h5>Current Scope Sharing</h5>
<p>While occasionally units of work are nested multiple layers deep, most of the time a single executable will deal with only one kind of unit of work.</p>
<p>In a web application, the ‘child’ scopes created from the root are for each HTTP request and might be tagged with <code class="codecolorer text default"><span class="text">&quot;httpRequest&quot;</span></code>. In a back-end process, we may also have a two-level scope hierarchy, but the child scopes may be per-<code class="codecolorer text default"><span class="text">&quot;workItem&quot;</span></code>.</p>
<p>Many kinds of components, for example those related to persistence or caching, need to be shared per unit of work, regardless of which application model the component is being used in. For these kinds of components, Autofac provides the <code class="codecolorer text default"><span class="text">InstancePerLifetimeScope()</span></code> sharing model.</p>
<p>If a component is configured to use an <code class="codecolorer text default"><span class="text">InstancePerLifetimeScope()</span></code> then at most a single instance of that component will be shared between all other components with the same lifetime, regardless of the level or tag associated with the scope they’re in. This is great for reusing components and configuration between different applications or services in the same solution.</p>
<h4>Lifetime Scopes don’t have any Context Dependency</h4>
<p>It is completely acceptable to create multiple independent lifetime scopes on the same thread:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">var ls1 <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
var ls2 <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
<span style="color: #008080; font-style: italic;">// ls1 and ls2 are completely independent of each other</span></div></div>
<p>It is also perfectly safe to share a single lifetime scope between many threads, and to end a lifetime scope on a thread other than the one that began it.</p>
<p>Lifetime scopes don’t rely on thread-local storage or global state like the HTTP context in order to do their work.</p>
<h4>Components can Create Lifetime Scopes</h4>
<p>The container can be used directly for creating lifetime scopes, but most of the time you won’t want to use a global container variable for this.</p>
<p>All a component needs to do to create and use lifetime scopes is to take a dependency on the <code class="codecolorer text default"><span class="text">ILifetimeScope</span></code> interface:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">class</span> MessageDispatcher <span style="color: #008000;">:</span> IMessageDispatcher<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; ILifetimeScope _lifetimeScope<span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> MessageDispatcher<span style="color: #008000;">&#40;</span>ILifetimeScope lifetimeScope<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; _lifetimeScope <span style="color: #008000;">=</span> lifetimeScope<span style="color: #008000;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnMessage<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> message<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var messageScope <span style="color: #008000;">=</span> _lifetimeScope<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginLifetimeScope</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var handler <span style="color: #008000;">=</span> messageScope<span style="color: #008000;">.</span><span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IMessageHandler<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler<span style="color: #008000;">.</span><span style="color: #0000FF;">Handle</span><span style="color: #008000;">&#40;</span>message<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>The <code class="codecolorer text default"><span class="text">ILifetimeScope</span></code> instance that is injected will be the one in which the component ‘lives.’</p>
<h3>Owned Instances</h3>
<p><a href='http://code.google.com/p/autofac/wiki/OwnedInstances'>Owned instances</a> (<code class="codecolorer text default"><span class="text">Owned&lt;T&gt;</span></code>) are the last tale in Autofac’s lifetime story.</p>
<p>An owned instance is a component that comes wrapped in its own lifetime scope. This makes it easier to keep track of how a component should be released, especially if it is used outside of a <code class="codecolorer text default"><span class="text">using</span></code> statement.</p>
<p>To get an owned instance providing service <code class="codecolorer text default"><span class="text">T</span></code>, you can resolve one directly from the container:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">var ownedService <span style="color: #008000;">=</span> container<span style="color: #008000;">.</span><span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>Owned<span style="color: #008000;">&lt;</span>IMyService<span style="color: #008000;">&gt;&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></div></div>
<p>In lifetime terms, this is equivalent to creating a new lifetime scope from the container, and resolving <code class="codecolorer text default"><span class="text">IMyService</span></code> from that. The only difference is that the <code class="codecolorer text default"><span class="text">IMyService</span></code> and the lifetime scope that holds it come wrapped up together in a single object.</p>
<p>The service implementation is available through the <code class="codecolorer text default"><span class="text">Value</span></code> property:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #008080; font-style: italic;">// Value is IMyService</span><br />
ownedService<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DoSomething</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></div></div>
<p>When the owned instance is no longer needed, it and all of its disposable dependencies can be released by disposing the <code class="codecolorer text default"><span class="text">Owned&lt;T&gt;</span></code> object:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">ownedService<span style="color: #008000;">.</span><span style="color: #0000FF;">Dispose</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></div></div>
<h4>Combining with Func Factories</h4>
<p>Autofac <a href='http://code.google.com/p/autofac/wiki/RelationshipTypes'>automatically provides</a> <code class="codecolorer text default"><span class="text">Func&lt;T&gt;</span></code> as a service when <code class="codecolorer text default"><span class="text">T</span></code> is registered. As we saw in an earlier example, components can use this mechanism to create instances of other components on the fly.</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">class</span> MyComponent2 <span style="color: #008000;">:</span> IMyService2<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; Func<span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;</span> _resourceFactory<span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> MyComponent<span style="color: #008000;">&#40;</span>Func<span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;</span> resourceFactory<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; _resourceFactory <span style="color: #008000;">=</span> resourceFactory<span style="color: #008000;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Go<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var r <span style="color: #008000;">=</span> _resourceFactory<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// Out of memory.</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Components that are returned from <code class="codecolorer text default"><span class="text">Func&lt;T&gt;</span></code> delegates are associated with the <em>same lifetime scope</em> as the delegate itself. If that component is itself contained in a lifetime scope, and it creates a finite number of instances through the delegate, then there’s no problem – everything will be cleaned up when the scope completes.</p>
<p>If the component calling the delegate is a long-lived one, then the instances returned from the delegate will need to be cleaned up eagerly. To do this, <code class="codecolorer text default"><span class="text">Owned&lt;T&gt;</span></code> can be used as the return value of a factory delegate:</p>
<div class="codecolorer-container csharp default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:800px;"><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6666cc; font-weight: bold;">class</span> MyComponent2 <span style="color: #008000;">:</span> IMyService2<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; Func<span style="color: #008000;">&lt;</span>Owned<span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;&gt;</span> _resourceFactory<span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> MyComponent<span style="color: #008000;">&#40;</span>Func<span style="color: #008000;">&lt;</span>Owned<span style="color: #008000;">&lt;</span>IMyResource<span style="color: #008000;">&gt;&gt;</span> resourceFactory<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; _resourceFactory <span style="color: #008000;">=</span> resourceFactory<span style="color: #008000;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Go<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var r <span style="color: #008000;">=</span> _resourceFactory<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008080; font-style: italic;">// Use r.Value before disposing it </span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p><code class="codecolorer text default"><span class="text">Func&lt;T&gt;</span></code> and <code class="codecolorer text default"><span class="text">Owned&lt;T&gt;</span></code> can be combined with other <a href='http://nblumhardt.com/2010/01/the-relationship-zoo/'>relationship types</a> to define relationships with a clearer intent than just taking a dependency on <code class="codecolorer text default"><span class="text">ILifetimeScope</span></code>.</p>
<h3>Do I really have to think about all this stuff?</h3>
<p>That concludes our tour of lifetime management with Autofac. Whether you use an IoC container or not, and whether you use Autofac or another IoC container, non-trivial applications have to deal with the kinds of issues we’ve discussed.</p>
<p>Once you’ve wrapped your mind around a few key concepts, you’ll find that lifetime rarely causes any headaches. On the plus side, a huge range of difficult application design problems around resource management and ownership will disappear.</p>
<p>Just remember:</p>
<ol>
<li>Autofac <strong>holds references</strong> to all the disposable components it creates</li>
<li>To prevent memory and resource leaks, always resolve components from <strong>lifetime scopes</strong> and dispose the scope at the conclusion of a task</li>
<li>Effectively using lifetime scopes requires that you clearly map out the <strong>unit of work</strong> structure of your applications</li>
<li><strong>Owned instances</strong> provide an abstraction over lifetime scopes that can be cleaner to work with</li>
</ol>
<p>Happy programming!</p>
]]></content:encoded>
			<wfw:commentRss>http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

