<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Nicholas Blumhardt (Ubik Systems)</title>
    <link>http://ubik.com.au/home</link>
    <pubDate>Sun, 27 Jul 2008 18:13:00 GMT</pubDate>
    <description>Ubik Systems Site Updates</description>
    <item>
      <title>Stateless</title>
      <link>http://ubik.com.au/article/named/stateless</link>
      <description>    &lt;p&gt;
        Our team recently needed to add fairly complex lifecycle to a couple of domain 
        objects.&lt;/p&gt;
    &lt;p&gt;
        &lt;a href="http://codeplex.com/simplestatemachine"&gt;Simple State Machine&lt;/a&gt; looked to fit the bill very nicely, but we 
        ended up going with an even simpler implementation in C# only (SSM uses a Boo e-DSL.)&lt;/p&gt;
    &lt;p&gt;
        The results were very usable, but the implementation well, wasn&amp;#39;t the nicest 
        piece of code I&amp;#39;d written. Sleeplessness motivated me to take another shot at 
        the problem, and the result is now on &lt;a href="http://stateless.googlecode.com"&gt;Google Code&lt;/a&gt; awating your scathing 
        criticism :)&lt;/p&gt;
    &lt;p&gt;
        BTW, yes, the title of the project is irony. My sense of humour really is that 
        bad.&lt;/p&gt;</description>
      <pubDate>Sun, 27 Jul 2008 18:13:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/stateless</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Some Great News!</title>
      <link>http://ubik.com.au/article/named/some_great_news</link>
      <description>    &lt;p&gt;
        I am extremely happy to be able to announce that I'm joining
        &lt;a href="http://blogs.msdn.com/kcwalina"&gt;Krzysztof Cwalina&amp;#39;s&lt;/a&gt; team
        at Microsoft!&lt;/p&gt;
    &lt;p&gt;
        My position will be Program Manager, and our team is building  
        &lt;a href="http://code.msdn.microsoft.com/mef"&gt;MEF&lt;/a&gt; (the &lt;em&gt;Managed Extensibility Framework&lt;/em&gt;)
        along with other projects.&lt;/p&gt;
    &lt;p&gt;
        MEF is really exciting - it&amp;#39;s set to be a unique and very useful addition 
        to the .NET Framework. Krzysztof and his team have a great vision for this project, and
        the opportunity to contribute directly is out of this world.&lt;/p&gt;
    &lt;p&gt;
        What makes this doubly exciting is that one of the visionaries
        of the ALT.NET world, &lt;a href="http://hammett.castleproject.org/"&gt;Hamilton Verissimo&lt;/a&gt;,
        founder of the &lt;a href="http://castleproject.org/"&gt;Castle Project&lt;/a&gt;,
        announced last night that he too is joining the team.&lt;/p&gt;
    &lt;p&gt;
        &lt;em&gt;Triply&lt;/em&gt; exciting is that P&amp;P guru &lt;a href="http://blogs.msdn.com/gblock/"&gt;
        Glen Block&lt;/a&gt; followed hot on the heels of Hamilton's announcement with news that
        he is doing the same.&lt;/p&gt;
    &lt;p&gt;
        What does this mean for &lt;a href="http://autofac.org"&gt;Autofac&lt;/a&gt;? Like Hamilton
        and Castle, I&amp;#39;ll still be able to contribute to Autofac, so there&amp;#39;s no need to
        fear for its future. Moving, exploring the United States, and the new job are 
        obviously going to consume a vast amount of my time, so if you&amp;#39;re interested in 
        propelling Autofac forwards there has never been a better time to
        lend a hand!&lt;/p&gt;
    &lt;p&gt;
        Right now there is a lot of organising to do - it is a big move and the next couple of months are 
        going to be really, really busy. (Extra special thanks, Suzi, for helping out so much 
        and putting up with all the mania!)&lt;/p&gt;
    &lt;p&gt;
        If you&amp;#39;re in the Seattle area I&amp;#39;d love to hear from you - I'll be in the country
        by early September, so drop me a line!&lt;/p&gt;</description>
      <pubDate>Thu, 17 Jul 2008 07:14:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/some_great_news</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Implementing the Specification Pattern via Linq</title>
      <link>http://ubik.com.au/article/named/implementing_the_specification_pattern_with_linq</link>
      <description>&lt;p&gt;Linq came with grand promises of bridging the object and relational worlds. Here&amp;apos;s one place that it succeeds very well.&lt;/p&gt;
    &lt;h3&gt;
        Queries and Predicates&lt;/h3&gt;
&lt;p&gt;
        Queries have historically sat uneasily alongside predicates in domain-driven designs.&lt;/p&gt;
    &lt;p&gt;
        The point of discomfort is that logic needs to be duplicated in different 
        representations for the dual purposes of evaluation an data access.&lt;/p&gt;
    &lt;p&gt;
        This is best illustrated by an example - in this case from a library system:&lt;/p&gt;
    &lt;pre&gt;public class Loan
{
  // Some details omitted

  public DateTime DateBorrowed { get; }
  
  public DateTime? DateReturned { get; set; }
  
  public bool IsOverdue
  {
    get
    {
      return DateReturned == null &amp;&amp;
        DateTime.Now - DateBorrowed &amp;gt; LoanPeriod;
    }
  }
}&lt;/pre&gt;
    &lt;p&gt;
        The &lt;code&gt;IsOverdue&lt;/code&gt; property encapsulates some of the logic from our 
        domain so that it can be utilised within the domain model. Whether or not a loan 
        is overdue is probably going to be significant in places dealing with the 
        individual loan - when it is displayed, or when the borrower seeks to renew 
        their library membership.&lt;/p&gt;
&lt;p&gt;
        Another typical use case for such a system might be an ability to bring up a list of 
        overdue books. To implement this efficiently, the &lt;code&gt;IsOverdue&lt;/code&gt;
        predicate needs to be expressed in a form that can select records from the database
        (here using NHibernate.Linq):&lt;/p&gt;
        &lt;pre&gt;public class LoanRepository
{
  public IEnumerable&amp;lt;Loan&amp;gt; FindOverdueBooks()
  {
    return from loan in _session.Linq&amp;lt;Loan&amp;gt;()
           where loan.DateReturned == null
           where DateTime.Now - DateBorrowed &amp;gt; Loan.LoanPeriod
           select loan;
  }
}&lt;/pre&gt;
&lt;p&gt;
This is obviously simplified, but you can see that even when using Linq it is 
    still necessary to duplicate the &lt;code&gt;IsOverdue&lt;/code&gt; predicate in a form that 
    can be used to query the database.&lt;/p&gt;
&lt;p&gt;
    In his book &lt;a href="http://www.domaindrivendesign.org/books/index.html#DDD"&gt;Domain Driven 
    Design&lt;/a&gt;, &lt;a href="http://www.domainlanguage.com/about/ericevans.html"&gt;Eric Evans&lt;/a&gt; discusses a 
    pattern that can come to the rescue, and when implemented using Linq, is better 
    than ever.&lt;/p&gt;
&lt;h3&gt;
    Specification&lt;/h3&gt;
&lt;p&gt;
    The essence of &lt;a href="http://en.wikipedia.org/wiki/Specification_pattern"&gt;&lt;i&gt;Specification&lt;/i&gt;&lt;/a&gt; is that the logic is extracted from the entity into a specification object:&lt;/p&gt;
    &lt;img class="centred" src="/article/download_attachment?attachment_id=13"  alt="Specification Pattern" /&gt;
    &lt;p&gt;
        The specification is part of the domain model, but gets used by the data access 
        layer to find matching items.&lt;/p&gt;
        &lt;p&gt;In this example, the specification is for overdue loans, so it might be represented by an
        &lt;code&gt;OverdueLoanSpecification&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;
        Within the domain model, the specification is used as a predicate:&lt;/p&gt;
&lt;pre&gt;public class Loan
{
  public bool IsOverdue
  {
    get
    {
      return new OverdueLoanSpecification().IsSatisfiedBy(this);
    }
  }
}&lt;/pre&gt;
    
    &lt;p&gt;
        Within the data access layer, the specification is used as a criterion:&lt;/p&gt;
    &lt;pre&gt;var loanRepository = new LoanRepository();
var specification = new OverdueLoanSpecification();
var overdueLoans = loanRepository.FindBySpecification(specification);&lt;/pre&gt;
    
    &lt;h3&gt;
        Implementing with Linq&lt;/h3&gt;
    &lt;p&gt;
        So, how can &lt;code&gt;OverdueLoanSpecification&lt;/code&gt; be implemented in a DRY and 
        optimal manner for both purposes?&lt;/p&gt;
&lt;p&gt;The answer turns out to be simple, and is a testament to the incredible elegance 
    of the design of Linq.&lt;/p&gt;
&lt;p&gt;First an abstract specification class:&lt;/p&gt;
&lt;pre&gt;public abstract class Specification&amp;lt;T&amp;gt;
{
  public bool IsSatisfiedBy(T item)
  {
    return SatisfyingElementsFrom(new[] { item }.AsQueryable()).Any();
  }
  
  public abstract IQueryable&amp;lt;T&amp;gt; SatisfyingElementsFrom(IQueryable&amp;lt;T&amp;gt; candidates);
}
&lt;/pre&gt;
&lt;p&gt;Implementers only need to define the query-based version - the predicate version is
implemented on top of it by the base class.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;OverdueLoanSpecification&lt;/code&gt; is part of the domain model:&lt;/p&gt;
&lt;pre&gt;public class OverdueLoanSpecification : Specification&amp;lt;Loan&amp;gt;
{
  public override IQueryable&amp;lt;T&amp;gt; SatisfyingElementsFrom(IQueryable&amp;lt;T&amp;gt; candidates)
  {
    return from loan in candidates
           where loan.DateReturned == null
           where DateTime.Now - DateBorrowed &amp;gt; Loan.LoanPeriod
           select loan;
  }
}
&lt;/pre&gt;
&lt;p&gt;Using a specification within a repository is straightforward, efficient, and preserves all of the
lazy-evaluation goodness that Linq brings:&lt;/p&gt;
&lt;pre&gt;public class Repository&amp;lt;T&amp;gt;
{
  public IQueryable&amp;lt;T&amp;gt; FindBySpecification(Specification&amp;lt;T&amp;gt specification)
  {
    return specification.SatisfyingElementsFrom(_session.Linq&amp;lt;T&amp;gt;());
  }
}
&lt;/pre&gt;
    
    &lt;p&gt;
        This example captures the essence of the solution, but there are obviously 
        plenty of refinements that should be made in practice. I&amp;#39;ve started building a more complete 
        an example as part of the &lt;a href="http://autofac.org"&gt;Autofac&lt;/a&gt; example 
        application - the curious can tinker with a very early version from
        &lt;a href="http://code.google.com/p/autofac/source/browse/trunk/src/Example/Remember.Model/Specification.cs"&gt;
        the Autofac Subversion repository&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;
        (The Autofac example is barely even a skeleton and probably shouldn&amp;#39;t be 
        construed as &amp;#39;best practice&amp;#39; at this stage.)&lt;/p&gt;
&lt;h3&gt;Advantages&lt;/h3&gt;
&lt;p&gt;I can see the following advantages of this implementation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Logic stays in one place, in the domain model, where it belongs&lt;/li&gt;
&lt;li&gt;Specifications are readily testable even without a database present&lt;/li&gt;
&lt;li&gt;Specifications are composable: chaining two calls to &lt;code&gt;SatisfyingElementsFrom()&lt;/code&gt; will result in only a single database query&lt;/li&gt;
&lt;li&gt;Interface bloat can be avoided in both the entity and the repository&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Downsides?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Potential circularity in the entity/specification relationship&lt;/li&gt;
&lt;li&gt;Unknown performance ramifications of &lt;code&gt;AsQueryable()&lt;/code&gt; under heavy usage&lt;/li&gt;
&lt;li&gt;A little bit less encapsulation in the entity class&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I'll definitely be using this pattern in the future - I'd love to hear of anyone's experiences in using it.&lt;/p&gt;</description>
      <pubDate>Sun, 06 Jul 2008 10:23:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/implementing_the_specification_pattern_with_linq</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Dependency Injection from a Behavioural Perspective</title>
      <link>http://ubik.com.au/article/named/dependency_injection_from_a_behavioural_perspective</link>
      <description>    &lt;p&gt;
        The basic concept of container-managed dependency injection has made its way 
        into mainstream .NET development. However, as
        &lt;a href="http://bradwilson.typepad.com"&gt;Brad Wilson&lt;/a&gt; observed in a
        &lt;a href="http://www.altnetpodcast.com/episodes/6-more-di-and-ioc"&gt;recent Alt.NET 
        Podcast&lt;/a&gt; with &lt;a href="http://kohari.org"&gt;Nate Kohari&lt;/a&gt;, we&amp;#39;re not yet 
        taking all of the opportunites that this new approach presents.&lt;/p&gt;
    &lt;p&gt;
        Here's my conjecture: I believe that the big change in thinking that we&amp;#39;re due for is to understand DI 
        containers from a &lt;strong&gt;dynamic, behavioural perspective&lt;/strong&gt; in addition to the 
        static, structural perspective in common use today.&lt;/p&gt;
    &lt;p&gt;
        Most developers view DI containers as a way to map interfaces or names (&lt;em&gt;services&lt;/em&gt;) 
        to implementation types (&lt;em&gt;components&lt;/em&gt;.) This interpretation is based 
        loosely on the idea of the container as a &lt;em&gt;map&lt;/em&gt; or &lt;a href="http://martinfowler.com/eaaCatalog/registry.html"&gt;
        &lt;em&gt;Registry&lt;/em&gt;&lt;/a&gt; with a recursive instantiation procedure attached.&lt;/p&gt;
    &lt;p&gt;
        This is a great way start off when explaining DI containers.
        &lt;a href="http://codebetter.com/blogs/jeremy.miller/"&gt;Jeremy Miller&amp;#39;s&lt;/a&gt;
        &lt;a href="http://structuremap.sourceforge.net"&gt;StructureMap&lt;/a&gt; was the first 
        successful .NET DI container (ca. 2004!) and in its name you can observe 
        Jeremy&amp;#39;s use of this metaphor in order to get the concept across.&lt;/p&gt;
    &lt;p&gt;
        The API models of most popular containers revolve around this mapping of services to implementations,
        and this in turn has shaped the way these containers are used.&lt;/p&gt;
    &lt;p&gt;
        The 'power users' of these frameworks however view them much more in the light of the 
        &lt;a href="http://en.wikipedia.org/wiki/Factory_Pattern"&gt;&lt;em&gt;Factory&lt;/em&gt;&lt;/a&gt; pattern(s).&lt;/p&gt;
    &lt;p&gt;
        &lt;em&gt;Factory&lt;/em&gt; and &lt;em&gt;Builder&lt;/em&gt; are at heart a behavioural patterns. Their essence is not so much 
        about hiding the concrete type of an instance, as hiding the process by which 
        that instance was created or located. &lt;a href="http://www.codeplex.com/ObjectBuilder"&gt;ObjectBuilder&lt;/a&gt;
        wholeheartedly embraced this dynamic role, but its positioning as a meta-DI framework
        limited its influence on the popular perception of DI.&lt;/p&gt;
    &lt;p&gt;
        Autofac has its roots in the world-view of &lt;a href="http://needle.rubyforge.org/api/"&gt;Needle&lt;/a&gt;.
        Autofac and Needle map services not to implementation types, but to functions that create component 
        instances. You can see this in Autofac&amp;#39;s name (it is an automated
        &lt;em&gt;Factory&lt;/em&gt;.)&lt;/p&gt;
    &lt;p&gt;
        This shift in perspective is one aspect of Autofac that is well-understood 
        and is getting used widely. A recent &lt;a href="http://groups.google.com/group/autofac/browse_thread/thread/b0ff5e5fce3a172a"&gt;
        example on the Autofac news group&lt;/a&gt; looked something
        like:&lt;/p&gt;
    &lt;pre&gt;
builder.Register(c =&amp;gt; someCondition ? (IUnitOfWork) new UnitOfWork() : new NullUnitOfWork())
  .ContainerScoped();&lt;/pre&gt;
    &lt;p&gt;
        Dynamic behaviour &lt;em&gt;is&lt;/em&gt; moving to the fore in other containers, too.
        &lt;a href="http://ninject.org"&gt;Ninject&lt;/a&gt; has a really interesting concept of
        &lt;a href="http://dojo.ninject.org/wiki/display/NINJECT/Contextual+Binding"&gt;&lt;em&gt;context&lt;/em&gt;&lt;/a&gt;
        that can be used in interesting ways, including through &lt;em&gt;match expressions&lt;/em&gt; which are
        evaluated at &lt;em&gt;resolve time&lt;/em&gt;.&lt;/p&gt;
    &lt;pre&gt;
// Pinched from the Ninject forum, thanks Frank!
container.Bind&amp;lt;IService&amp;gt;()
  .To&amp;lt;ServiceB&amp;gt;()
  .Only(When.Context.Matches(c =&amp;gt; c.Member.ReflectedType == typeof(Bar)));&lt;/pre&gt;
    &lt;p&gt;
        This kind of thing is being done elsewhere, too. For example
        &lt;a href="http://www.castleproject.org/container/index.html"&gt;Windsor&lt;/a&gt;
        is flexible enough that &lt;a href="http://blechie.com/WPierce"&gt;Bill Pierce&lt;/a&gt; has created a 
        &lt;a href="http://blechie.com/WPierce/archive/2006/09/30/Castle_MicroKernel__Whats_in_a_Name.aspx"&gt;
        dynamic name resolution extension&lt;/a&gt; for it.&lt;/p&gt;
    &lt;p&gt;
        &lt;a href="http://codeplex.com/unity"&gt;Unity&lt;/a&gt; has a &lt;em&gt;static factory&lt;/em&gt; extension that 
        provides some of the features of Autofac&amp;#39;s lambda registrations. Unity also inherits
        ObjectBuilder's &lt;em&gt;build chain&lt;/em&gt; architecture which provides a super-flexible way of
        adding behaviour to the build process.&lt;/p&gt;
    &lt;p&gt;
        Selection of an implementer is just the tip of the iceberg when considering how behaviour and logic can
        be applied in the activation process.&lt;/p&gt;
    &lt;p&gt;
        Autofac itself will go further in this direction. The &lt;code&gt;OnActivated()&lt;/code&gt; hook is one
        place where there might be some new possibilities in a future version:&lt;/p&gt;
    &lt;pre&gt;
builder.OnActivating&amp;lt;ICache&amp;gt;(cache =&amp;gt; cache.WarmUp());&lt;/pre&gt;
    &lt;p&gt;
        This (imagined) example would go some way towards the kind of functionality that
        the 'startable' facility would otherwise be use for, while expressing intent more
        clearly.&lt;/p&gt;
    &lt;p&gt;
        Autofac also has an &lt;code&gt;IRegistrationSource&lt;/code&gt; extension point that can be used
        to register components on the fly as they're requested from the container. This is used in a
        few places currently, like the open generic type support, and the
        &lt;code&gt;RegisterTypesAssignableTo(Type)&lt;/code&gt; shortcut, but could be used
        to implement tricks like naming schemes on top of the container:&lt;/p&gt;
    &lt;pre&gt;
builder.RegisterFromName(
  name =&gt; name.StartsWith("command."),
  (reg, name) =&gt; reg.Register(FindCommandType(name)).FactoryScoped());&lt;/pre&gt;
    &lt;p&gt;
        Food for thought, anyway.&lt;/p&gt;
    &lt;p&gt;
        The point I'd like to make with this post is that in most cases, the behavioural aspects of
        containers have been kept 'under the covers' and exposed to users through advanced
        API concepts like &lt;em&gt;container extensions&lt;/em&gt;.&lt;/p&gt;
    &lt;p&gt;
        A wider appreciation of the behavioural possibilities in DI containers is going to push more
        dynamic behaviour into the first-class APIs of containers. Dynamic behaviour is going to be
        planted firmly in the realm of container &lt;em&gt;configuration&lt;/em&gt; rather than container &lt;em&gt;extension&lt;/em&gt;.&lt;/p&gt;
    &lt;p&gt;
        You can see in most of these examples one key facilitator for changing this. Lambda expressions
        in C# 3.0 make behavioural configuration possible in a terse manner without relying on
        subclassing or interface implementation.&lt;/p&gt;
    &lt;p&gt;
        This is going to have a direct effect on the perceptions of developers who are using DI,
        and I think it has the potential to open up new roles for DI containers within
        application architectures.&lt;/p&gt;</description>
      <pubDate>Sun, 29 Jun 2008 14:17:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/dependency_injection_from_a_behavioural_perspective</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Autofac and AutofacContrib 1.2 Released</title>
      <link>http://ubik.com.au/article/named/autofac_and_autofaccontrib_12_released</link>
      <description>&lt;p&gt;Two months and 400+ downloads since the release of version 1.1, a new public release of Autofac is available.&lt;/p&gt;
&lt;p&gt;The 1.2 release is evolutionary, and for the most part refines the functionality available in 1.1.&lt;/p&gt;
&lt;p&gt;1.2 is accompanied by a separate release of the &lt;a href="http://autofac-contrib.googlecode.com"&gt;AutofacContrib&lt;/a&gt; project, aimed at distributing third-party integration modules and extended features for Autofac.&lt;/p&gt;
&lt;p&gt;Many thanks to the fantastic Autofac contributors, users and supporters who have built the momentum that the project now has.&lt;/p&gt;</description>
      <pubDate>Tue, 20 May 2008 11:54:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/autofac_and_autofaccontrib_12_released</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>AOP with Autofac and DynamicProxy2</title>
      <link>http://ubik.com.au/article/named/aop_with_autofac_and_dynamicproxy2</link>
      <description>	&lt;p&gt;Many developers will be familiar with the use of DynamicProxy from &lt;a href="http://castleproject.org"&gt;the Castle Project&lt;/a&gt;
	for method interception.&lt;/p&gt;
	&lt;p&gt;The latest &lt;a href="http://autofac-contrib.googlecode.com"&gt;AutofacContrib&lt;/a&gt; binary release includes a small library to make
	using DynamicProxy with Autofac easier.&lt;/p&gt;
	&lt;p&gt;&lt;a href="http://code.google.com/p/autofac-contrib/wiki/DynamicProxy2"&gt;AutofacContrib.DynamicProxy2&lt;/a&gt; provides functionality
	for attaching DynamicProxy interceptors to Autofac components.&lt;/p&gt;
	&lt;p&gt;Setting up the integration requires that the interception module is registered:&lt;/p&gt;
&lt;pre&gt;
builder.RegisterModule(new StandardInterceptionModule());
&lt;/pre&gt;
	&lt;p&gt;An example component exposing a single service:&lt;/p&gt;
&lt;pre&gt;
public interface ICalculator
{
    int Add(int lhs, int rhs);
    int Multiply(int lhs, int rhs);
}

[Intercept("log-calls")]
public class Calculator : ICalculator
{
    public virtual int Add(int lhs, int rhs)
    {
        return lhs + rhs;
    }

    public virtual int Multiply(int lhs, int rhs)
    {
        return lhs * rhs;
    }
}
&lt;/pre&gt;
	&lt;p&gt;Note the &lt;code&gt;Intercept&lt;/code&gt; attribute on the component implementation. The string &lt;code&gt;"log-calls"&lt;/code&gt; is the
	service providing &lt;code&gt;IInterceptor&lt;/code&gt; that will be attached to the component instances.&lt;/p&gt;
	&lt;p&gt;In this example, the &lt;code&gt;CallLogger&lt;/code&gt; component will be used to provide the log-calls service:&lt;/p&gt;
&lt;pre&gt;
public class CallLogger : IInterceptor
{
    TextWriter _output;

    public CallLogger(TextWriter output)
    {
        _output = output;
    }

    public void Intercept(IInvocation invocation)
    {
        _output.Write("Calling method {0} with parameters {1}... ",
            invocation.Method.Name,
            string.Join(", ", invocation.Arguments.Select(a =&amp;gt; (a ?? "").ToString()).ToArray()));

        invocation.Proceed();

        _output.WriteLine("Done: result was {0}.", invocation.ReturnValue);
    }
}
&lt;/pre&gt;
    &lt;p&gt;The interceptor is just a component like any other. A complete application shows the configuration of the interceptor:&lt;/p&gt;
&lt;pre&gt;
class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();
        
        builder.Register&amp;lt;Calculator&amp;gt;()
            .As&amp;lt;ICalculator&amp;gt;();
        
        builder.Register(c =&amp;gt; new CallLogger(Console.Out))
            .Named("log-calls");
        
        builder.RegisterModule(new StandardInterceptionModule());

        using (var container = builder.Build())
        {
            var calculator = container.Resolve&amp;lt;ICalculator&amp;gt;();
            var result = calculator.Add(1, calculator.Multiply(2, 3));
            Console.WriteLine("Complete, program result is {0}.", result);
            Console.ReadKey();
        }
    }
}
&lt;/pre&gt;
    &lt;p&gt;The output of the application is:&lt;/p&gt;
&lt;pre&gt;
Calling method Multiply with parameters 2, 3... Done: result was 6.
Calling method Add with parameters 1, 6... Done: result was 7.
Complete, program result is 7.
&lt;/pre&gt;
    &lt;p&gt;There are a few things worth noting:&lt;/p&gt;
    &lt;ul&gt;
        &lt;li&gt;&lt;code&gt;CallLogger&lt;/code&gt; has a dependency on the &lt;code&gt;TextWriter&lt;/code&gt;
        to which the log will be written, and this can be injected as usual&lt;/li&gt;
        &lt;li&gt;Interceptors can have factory, singleton or container scope like other components&lt;/li&gt;
        &lt;li&gt;This example could use &lt;code&gt;Intercept(typeof(CallLogger))]&lt;/code&gt; for exactly the same
        result, however, using service names keeps implementation type coupling to a minimum&lt;/li&gt;
        &lt;li&gt;If you're lazy and don't want to register all of your interceptors, you can use the
        &lt;code&gt;Intercept(Type)&lt;/code&gt; attribute constructor and set up your container with
        &lt;code&gt;builder.RegisterTypesAssignableTo&amp;lt;IInterceptor&amp;gt;()&lt;/code&gt;&lt;/li&gt;
        &lt;li&gt;To use interceptors with expression- or instance-registered components, use the
        &lt;code&gt;FlexibleInterceptionModule&lt;/code&gt; instead of the standard one - this will enable
        proxying through interfaces in these scenarios&lt;/li&gt;
    &lt;/ul&gt;
    &lt;p&gt;If you want to run this yourself, the complete solution is attached to this article.&lt;/p&gt;
    &lt;p&gt;Kudos to the Castle team for making DynamicProxy available - fantastic work, guys!&lt;/p&gt;
    &lt;p&gt;&lt;strong&gt;A quick aside:&lt;/strong&gt; if you're not already subscribed, take a look at
    &lt;a href="http://iridescence.no"&gt;Fredrik Kalseth's&lt;/a&gt; excellent blog. His recent series
    of well-written articles cover application design and unit testing with ASP.NET MVC, Linq to
    SQL, and Autofac. Anyone looking for some pointers in the right direction with these technologies
    will need to look no further.&lt;/p&gt;
</description>
      <pubDate>Mon, 19 May 2008 07:32:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/aop_with_autofac_and_dynamicproxy2</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Autofac on CodeProject</title>
      <link>http://ubik.com.au/article/named/autofac_on_codeproject</link>
      <description>&lt;p&gt;I've been wanting to write an introductory, from-the-ground-up article on Autofac for a while, and &lt;a href="http://www.codeproject.com/KB/architecture/di-with-autofac.aspx"&gt;here it is!&lt;/a&gt;&lt;/p&gt;</description>
      <pubDate>Sat, 19 Apr 2008 18:27:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/autofac_on_codeproject</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Good Citizenship</title>
      <link>http://ubik.com.au/article/named/good_citizenship</link>
      <description>&lt;p&gt;This &lt;a href="http://docs.codehaus.org/display/PICO/Good+Citizen"&gt;set of design principles&lt;/a&gt; is a few years old, but I'm not sure how widely it is referenced. I can't even remember who originally pointed me towards it...&lt;/p&gt;
&lt;p&gt;There are a couple of Java-centric points, but its still absolutely invaluable advice for designing robust classes in .NET.&lt;/p&gt;
&lt;p&gt;I especially like 'never expect or return null' - how much easier would our lives be if ever API followed this convention?&lt;/p&gt;</description>
      <pubDate>Fri, 28 Mar 2008 19:42:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/good_citizenship</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Autofac turns 1.1</title>
      <link>http://ubik.com.au/article/named/autofac_turns_11</link>
      <description>&lt;p&gt;Thanks to the continuous input and support of the growing &lt;a href="http://autofac.org"&gt;Autofac&lt;/a&gt; &lt;a href="http://googlegroups.com/group/autofac"&gt;community&lt;/a&gt;, the best release yet is now available to &lt;a href="http://code.google.com/p/autofac/downloads/list"&gt;download&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If you haven't tried it, there has never been a better time! Autofac is 
a fully-featured IoC container for .NET that makes building sophisticated component-oriented
architectures easier than ever before.&lt;/p&gt;</description>
      <pubDate>Wed, 19 Mar 2008 20:58:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/autofac_turns_11</guid>
      <author>Nicholas Blumhardt</author>
    </item>
    <item>
      <title>Enabling Rich Domain Models with Services</title>
      <link>http://ubik.com.au/article/named/enabling_rich_domain_models_with_services</link>
      <description>&lt;p&gt;&lt;a href="http://rabdullin.com"&gt;Rinat Abdullin&lt;/a&gt; has just posted an interesting
article that cuts to the core of a very tricky problem that you face building
applications on top of IoC:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Components often need to create instances of other container-managed
components at will.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Calling &lt;code&gt;new&lt;/code&gt; is a simple and natural thing to do in a non-DI
application, but takes more care when using DI. After all, avoiding the use of
&lt;code&gt;new&lt;/code&gt; is half of what DI is about.&lt;/p&gt;
&lt;p&gt;If you haven't read Rinat's
&lt;a href="http://rabdullin.com/how-to-avoid-tight-ioc-coupling-in-non-deterministic-resolution-scenarios"&gt;article&lt;/a&gt;,
head over and check it out. (Rinat doesn't just contribute code and &lt;a href="http://groups.google.com/group/autofac_ci"&gt;
CPU cycles&lt;/a&gt; to the Autofac
project, but also a large number of brain-cycles.)&lt;/p&gt;
&lt;p&gt;The solution is to create adapters that bridge the
gap between components in the container, and the container itself. This is done
using an interface that is independent of the container, to keep
the components free of dependencies on the container, which I must reiterate,
is &lt;strong&gt;the&lt;/strong&gt; rule.&lt;/p&gt;
&lt;p&gt;The reason this problem interests me so much is that it is so common but
so infrequently addressed. One of my great passions is for domain-driven design, and
I'm always looking for ways to make a domain model richer.&lt;/p&gt;
&lt;p&gt;A typically contrived example is determining the current value of a holding
of stock:&lt;/p&gt;
&lt;pre&gt;
public class Shareholding
{
  public Shareholding(string symbol, int quantity) {...}
  public string Symbol { get {...} }
  public int Quantity { get {...} }
}
&lt;/pre&gt;
&lt;p&gt;To get the current value of a holding, we can use a quote service:&lt;/p&gt;
&lt;pre&gt;
public interface IQuoteService
{
  decimal GetQuote(string symbol);
}
&lt;/pre&gt;
&lt;p&gt;All of this is well and good - determining the value of a holding is a simple
operation and the quote service can obviously be injected into whichever controller
is going to do the calculation.&lt;/p&gt;
&lt;p&gt;An incremental improvement though is to encapsulate the logic in a property
of the &lt;code&gt;Shareholding&lt;/code&gt; class itself. Perhaps we'll set the quote service
as an optional dependency:&lt;/p&gt;
&lt;pre&gt;
public class Shareholding
{
  public IQuoteService QuoteService { set; private get; }
  public decimal Current Value
  {
    get
    {
      return QuoteService.GetQuote(Symbol) * Quantity;
    }
  }
  ...
&lt;/pre&gt;
&lt;p&gt;To get the value:&lt;/p&gt;
&lt;pre&gt;
// In some method...
var shareholding = new Shareholding("ABC", 1000);
shareholding.QuoteService = this.QuoteService;
Console.WriteLine(shareholding.Value);
&lt;/pre&gt;
&lt;p&gt;Spot the problem? Any class that wants to create shareholdings must itself have
reference to an &lt;code&gt;IQuoteService&lt;/code&gt; so that it can manually inject the dependency.&lt;/p&gt;
&lt;p&gt;This breaks some of the encapsulation that we were originally trying to achieve by
exposing &lt;code&gt;Shareholding&lt;/code&gt;'s reliance on the service. This isn't so bad if the caller is created directly by the container, but if not, it has a flow-on effect
through all components that create instances of other components - if &lt;code&gt;Shareholding&lt;/code&gt;
then creates more components themselves with dependencies, we're in real trouble. Every component along the line will have to obtain a reference to an &lt;code&gt;IQuoteService&lt;/code&gt; and pass this along.&lt;/p&gt;
&lt;p&gt;Now, that's the context of our problem. In Rinat's example, which deals with
executing workflows, a hand-coded factory encapsulating a reference to the container
is a rather nice solution. When building a domain model with hundreds of interrelated classes
that all may create instances of each other, this becomes impractical in my eyes.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Aside: &lt;a href="http://udidahan.weblogs.us/2008/02/29/how-to-create-fully-encapsulated-domain-models/"&gt;
Udi Dahan&lt;/a&gt;, a man who knows more than a little about DDD, posted an article on his solution
while I was writing this. Udi's solution uses events and looks very workable, but appears as though
it might exhibit increasing complexity as the depth of dependencies within the domain model increases.
I could certainly be wrong and definitely need to spend some more time investigating Udi's model.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A syntactic shortcut that Rinat has touched on and that I am interested in exploring further
is to utilise .NET's typing features to substitute delegate signatures for the adapter/resolver
interfaces:&lt;/p&gt;
&lt;pre&gt;
public class Shareholding
{
  public delegate Shareholding Factory(string symbol, int quantity);
  public Shareholding(string symbol, int quantity) {...}
  ...
&lt;/pre&gt;
&lt;p&gt;We can register an instance of this delegate in the container:&lt;/p&gt;
&lt;pre&gt;
builder.Register&amp;lt;Shareholding&amp;gt;().FactoryScoped();
builder.RegisterGeneratedFactory&amp;lt;Shareholding.Factory&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;This lets us later resolve that factory delegate as a dependency, and use it to create
our &lt;code&gt;Shareholding&lt;/code&gt; without any awareness of the injected quote service:&lt;/p&gt;
&lt;pre&gt;
// In some method...
var shareholding = this.ShareholdingFactory("ABC", 1000);
Console.WriteLine(shareholding.Value);
&lt;/pre&gt;
&lt;p&gt;I cheated a bit just there. What the &lt;code&gt;RegisterGeneratedFactory()&lt;/code&gt; method does,
is (approximately):&lt;/p&gt;
&lt;pre&gt;
builder.Register&amp;lt;Shareholding.Factory&amp;gt;(
  (c, p) =&amp;gt;
    (symbol, quantity) =&amp;gt;
      c.Resolve&amp;lt;Shareholding&amp;gt;(new Parameter("symbol", symbol), new Parameter("quantity", quantity)))
  .ContainerScoped();
&lt;/pre&gt;
&lt;p&gt;Now that is a mouthful of lambda! Autofac 1.1 uses Linq to translate the parameters of the
&lt;code&gt;Shareholding.Factory&lt;/code&gt; delegate, &lt;code&gt;symbol&lt;/code&gt; and &lt;code&gt;quantity&lt;/code&gt; into
named parameters that can be fed to the container's &lt;code&gt;Shareholding&lt;/code&gt; constructor call.&lt;/p&gt;
&lt;p&gt;At the moment I feel like this kind of container usage is really on the edge and perhaps
you should expect some less exotic scenarios in my future posts, however DI/IoC is a very 
deep architectural pattern, and in the coming years (before it eliminated entirely by languages
without the structural object creation issues we face in C#,)
lots of people are going to hit these same
challenges. I hope that we can take some of these concepts along with Autofac to make solving
these problems more straightforward.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Closing note - you need a pretty flexible ORM, like &lt;a href="http://nibernate.org"&gt;NHibernate&lt;/a&gt;
before you'll get very far trying to pull tricks like this with your domain model ;)&lt;/p&gt;</description>
      <pubDate>Sun, 02 Mar 2008 13:07:00 GMT</pubDate>
      <guid>http://ubik.com.au/article/named/enabling_rich_domain_models_with_services</guid>
      <author>Nicholas Blumhardt</author>
    </item>
  </channel>
</rss>
