Log in

Subscribe to site updates.

Nicholas Blumhardt

Nicholas Blumhardt

Stateless

Posted by Nicholas Blumhardt | July 27, 2008 18:13

Our team recently needed to add fairly complex lifecycle to a couple of domain objects.

Simple State Machine 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.)

The results were very usable, but the implementation well, wasn't the nicest piece of code I'd written. Sleeplessness motivated me to take another shot at the problem, and the result is now on Google Code awating your scathing criticism :)

BTW, yes, the title of the project is irony. My sense of humour really is that bad.

1 comment.

Nicholas Blumhardt

Some Great News!

Posted by Nicholas Blumhardt | July 17, 2008 07:14

I am extremely happy to be able to announce that I'm joining Krzysztof Cwalina's team at Microsoft!

My position will be Program Manager, and our team is building MEF (the Managed Extensibility Framework) along with other projects.

MEF is really exciting - it'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.

What makes this doubly exciting is that one of the visionaries of the ALT.NET world, Hamilton Verissimo, founder of the Castle Project, announced last night that he too is joining the team.

Triply exciting is that P&P guru Glen Block followed hot on the heels of Hamilton's announcement with news that he is doing the same.

What does this mean for Autofac? Like Hamilton and Castle, I'll still be able to contribute to Autofac, so there'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're interested in propelling Autofac forwards there has never been a better time to lend a hand!

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!)

If you're in the Seattle area I'd love to hear from you - I'll be in the country by early September, so drop me a line!

14 comments.

Nicholas Blumhardt

Implementing the Specification Pattern via Linq

Posted by Nicholas Blumhardt | July 06, 2008 10:23

Linq came with grand promises of bridging the object and relational worlds. Here's one place that it succeeds very well.

Queries and Predicates

Queries have historically sat uneasily alongside predicates in domain-driven designs.

The point of discomfort is that logic needs to be duplicated in different representations for the dual purposes of evaluation an data access.

This is best illustrated by an example - in this case from a library system:

public class Loan
{
  // Some details omitted

  public DateTime DateBorrowed { get; }
  
  public DateTime? DateReturned { get; set; }
  
  public bool IsOverdue
  {
    get
    {
      return DateReturned == null &&
        DateTime.Now - DateBorrowed > LoanPeriod;
    }
  }
}

The IsOverdue 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.

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 IsOverdue predicate needs to be expressed in a form that can select records from the database (here using NHibernate.Linq):

public class LoanRepository
{
  public IEnumerable<Loan> FindOverdueBooks()
  {
    return from loan in _session.Linq<Loan>()
           where loan.DateReturned == null
           where DateTime.Now - DateBorrowed > Loan.LoanPeriod
           select loan;
  }
}

This is obviously simplified, but you can see that even when using Linq it is still necessary to duplicate the IsOverdue predicate in a form that can be used to query the database.

In his book Domain Driven Design, Eric Evans discusses a pattern that can come to the rescue, and when implemented using Linq, is better than ever.

Specification

The essence of Specification is that the logic is extracted from the entity into a specification object:

Specification Pattern

The specification is part of the domain model, but gets used by the data access layer to find matching items.

In this example, the specification is for overdue loans, so it might be represented by an OverdueLoanSpecification.

Within the domain model, the specification is used as a predicate:

public class Loan
{
  public bool IsOverdue
  {
    get
    {
      return new OverdueLoanSpecification().IsSatisfiedBy(this);
    }
  }
}

Within the data access layer, the specification is used as a criterion:

var loanRepository = new LoanRepository();
var specification = new OverdueLoanSpecification();
var overdueLoans = loanRepository.FindBySpecification(specification);

Implementing with Linq

So, how can OverdueLoanSpecification be implemented in a DRY and optimal manner for both purposes?

The answer turns out to be simple, and is a testament to the incredible elegance of the design of Linq.

First an abstract specification class:

public abstract class Specification<T>
{
  public bool IsSatisfiedBy(T item)
  {
    return SatisfyingElementsFrom(new[] { item }.AsQueryable()).Any();
  }
  
  public abstract IQueryable<T> SatisfyingElementsFrom(IQueryable<T> candidates);
}

Implementers only need to define the query-based version - the predicate version is implemented on top of it by the base class.

The OverdueLoanSpecification is part of the domain model:

public class OverdueLoanSpecification : Specification<Loan>
{
  public override IQueryable<T> SatisfyingElementsFrom(IQueryable<T> candidates)
  {
    return from loan in candidates
           where loan.DateReturned == null
           where DateTime.Now - DateBorrowed > Loan.LoanPeriod
           select loan;
  }
}

Using a specification within a repository is straightforward, efficient, and preserves all of the lazy-evaluation goodness that Linq brings:

public class Repository<T>
{
  public IQueryable<T> FindBySpecification(Specification<T> specification)
  {
    return specification.SatisfyingElementsFrom(_session.Linq<T>());
  }
}

This example captures the essence of the solution, but there are obviously plenty of refinements that should be made in practice. I've started building a more complete an example as part of the Autofac example application - the curious can tinker with a very early version from the Autofac Subversion repository.

(The Autofac example is barely even a skeleton and probably shouldn't be construed as 'best practice' at this stage.)

Advantages

I can see the following advantages of this implementation:

  • Logic stays in one place, in the domain model, where it belongs
  • Specifications are readily testable even without a database present
  • Specifications are composable: chaining two calls to SatisfyingElementsFrom() will result in only a single database query
  • Interface bloat can be avoided in both the entity and the repository

Downsides?

  • Potential circularity in the entity/specification relationship
  • Unknown performance ramifications of AsQueryable() under heavy usage
  • A little bit less encapsulation in the entity class

I'll definitely be using this pattern in the future - I'd love to hear of anyone's experiences in using it.

12 comments.

Nicholas Blumhardt

Dependency Injection from a Behavioural Perspective

Posted by Nicholas Blumhardt | June 29, 2008 14:17

The basic concept of container-managed dependency injection has made its way into mainstream .NET development. However, as Brad Wilson observed in a recent Alt.NET Podcast with Nate Kohari, we're not yet taking all of the opportunites that this new approach presents.

Here's my conjecture: I believe that the big change in thinking that we're due for is to understand DI containers from a dynamic, behavioural perspective in addition to the static, structural perspective in common use today.

Most developers view DI containers as a way to map interfaces or names (services) to implementation types (components.) This interpretation is based loosely on the idea of the container as a map or Registry with a recursive instantiation procedure attached.

This is a great way start off when explaining DI containers. Jeremy Miller's StructureMap was the first successful .NET DI container (ca. 2004!) and in its name you can observe Jeremy's use of this metaphor in order to get the concept across.

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.

The 'power users' of these frameworks however view them much more in the light of the Factory pattern(s).

Factory and Builder 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. ObjectBuilder wholeheartedly embraced this dynamic role, but its positioning as a meta-DI framework limited its influence on the popular perception of DI.

Autofac has its roots in the world-view of Needle. Autofac and Needle map services not to implementation types, but to functions that create component instances. You can see this in Autofac's name (it is an automated Factory.)

This shift in perspective is one aspect of Autofac that is well-understood and is getting used widely. A recent example on the Autofac news group looked something like:

builder.Register(c => someCondition ? (IUnitOfWork) new UnitOfWork() : new NullUnitOfWork())
  .ContainerScoped();

Dynamic behaviour is moving to the fore in other containers, too. Ninject has a really interesting concept of context that can be used in interesting ways, including through match expressions which are evaluated at resolve time.

// Pinched from the Ninject forum, thanks Frank!
container.Bind<IService>()
  .To<ServiceB>()
  .Only(When.Context.Matches(c => c.Member.ReflectedType == typeof(Bar)));

This kind of thing is being done elsewhere, too. For example Windsor is flexible enough that Bill Pierce has created a dynamic name resolution extension for it.

Unity has a static factory extension that provides some of the features of Autofac's lambda registrations. Unity also inherits ObjectBuilder's build chain architecture which provides a super-flexible way of adding behaviour to the build process.

Selection of an implementer is just the tip of the iceberg when considering how behaviour and logic can be applied in the activation process.

Autofac itself will go further in this direction. The OnActivated() hook is one place where there might be some new possibilities in a future version:

builder.OnActivating<ICache>(cache => cache.WarmUp());

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.

Autofac also has an IRegistrationSource 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 RegisterTypesAssignableTo(Type) shortcut, but could be used to implement tricks like naming schemes on top of the container:

builder.RegisterFromName(
  name => name.StartsWith("command."),
  (reg, name) => reg.Register(FindCommandType(name)).FactoryScoped());

Food for thought, anyway.

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 container extensions.

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 configuration rather than container extension.

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.

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.

0 comments.

Nicholas Blumhardt

AOP with Autofac and DynamicProxy2

Posted by Nicholas Blumhardt | May 19, 2008 07:32

Many developers will be familiar with the use of DynamicProxy from the Castle Project for method interception.

The latest AutofacContrib binary release includes a small library to make using DynamicProxy with Autofac easier.

AutofacContrib.DynamicProxy2 provides functionality for attaching DynamicProxy interceptors to Autofac components.

Setting up the integration requires that the interception module is registered:

builder.RegisterModule(new StandardInterceptionModule());

An example component exposing a single service:

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;
    }
}

Note the Intercept attribute on the component implementation. The string "log-calls" is the service providing IInterceptor that will be attached to the component instances.

In this example, the CallLogger component will be used to provide the log-calls service:

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 => (a ?? "").ToString()).ToArray()));

        invocation.Proceed();

        _output.WriteLine("Done: result was {0}.", invocation.ReturnValue);
    }
}

The interceptor is just a component like any other. A complete application shows the configuration of the interceptor:

class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();
        
        builder.Register<Calculator>()
            .As<ICalculator>();
        
        builder.Register(c => new CallLogger(Console.Out))
            .Named("log-calls");
        
        builder.RegisterModule(new StandardInterceptionModule());

        using (var container = builder.Build())
        {
            var calculator = container.Resolve<ICalculator>();
            var result = calculator.Add(1, calculator.Multiply(2, 3));
            Console.WriteLine("Complete, program result is {0}.", result);
            Console.ReadKey();
        }
    }
}

The output of the application is:

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.

There are a few things worth noting:

  • CallLogger has a dependency on the TextWriter to which the log will be written, and this can be injected as usual
  • Interceptors can have factory, singleton or container scope like other components
  • This example could use Intercept(typeof(CallLogger))] for exactly the same result, however, using service names keeps implementation type coupling to a minimum
  • If you're lazy and don't want to register all of your interceptors, you can use the Intercept(Type) attribute constructor and set up your container with builder.RegisterTypesAssignableTo<IInterceptor>()
  • To use interceptors with expression- or instance-registered components, use the FlexibleInterceptionModule instead of the standard one - this will enable proxying through interfaces in these scenarios

If you want to run this yourself, the complete solution is attached to this article.

Kudos to the Castle team for making DynamicProxy available - fantastic work, guys!

A quick aside: if you're not already subscribed, take a look at Fredrik Kalseth's 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.

Files

3 comments.

Nicholas Blumhardt

Autofac on CodeProject

Posted by Nicholas Blumhardt | April 19, 2008 18:27

I've been wanting to write an introductory, from-the-ground-up article on Autofac for a while, and here it is!

0 comments.

Nicholas Blumhardt

Good Citizenship

Posted by Nicholas Blumhardt | March 28, 2008 19:42

This set of design principles 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...

There are a couple of Java-centric points, but its still absolutely invaluable advice for designing robust classes in .NET.

I especially like 'never expect or return null' - how much easier would our lives be if ever API followed this convention?

0 comments.

Nicholas Blumhardt

Enabling Rich Domain Models with Services

Posted by Nicholas Blumhardt | March 02, 2008 13:07

Rinat Abdullin 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:

Components often need to create instances of other container-managed components at will.

Calling new 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 new is half of what DI is about.

If you haven't read Rinat's article, head over and check it out. (Rinat doesn't just contribute code and CPU cycles to the Autofac project, but also a large number of brain-cycles.)

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 the rule.

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.

A typically contrived example is determining the current value of a holding of stock:

public class Shareholding
{
  public Shareholding(string symbol, int quantity) {...}
  public string Symbol { get {...} }
  public int Quantity { get {...} }
}

To get the current value of a holding, we can use a quote service:

public interface IQuoteService
{
  decimal GetQuote(string symbol);
}

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.

An incremental improvement though is to encapsulate the logic in a property of the Shareholding class itself. Perhaps we'll set the quote service as an optional dependency:

public class Shareholding
{
  public IQuoteService QuoteService { set; private get; }
  public decimal Current Value
  {
    get
    {
      return QuoteService.GetQuote(Symbol) * Quantity;
    }
  }
  ...

To get the value:

// In some method...
var shareholding = new Shareholding("ABC", 1000);
shareholding.QuoteService = this.QuoteService;
Console.WriteLine(shareholding.Value);

Spot the problem? Any class that wants to create shareholdings must itself have reference to an IQuoteService so that it can manually inject the dependency.

This breaks some of the encapsulation that we were originally trying to achieve by exposing Shareholding'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 Shareholding 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 IQuoteService and pass this along.

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.

Aside: Udi Dahan, 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.

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:

public class Shareholding
{
  public delegate Shareholding Factory(string symbol, int quantity);
  public Shareholding(string symbol, int quantity) {...}
  ...

We can register an instance of this delegate in the container:

builder.Register<Shareholding>().FactoryScoped();
builder.RegisterGeneratedFactory<Shareholding.Factory>();

This lets us later resolve that factory delegate as a dependency, and use it to create our Shareholding without any awareness of the injected quote service:

// In some method...
var shareholding = this.ShareholdingFactory("ABC", 1000);
Console.WriteLine(shareholding.Value);

I cheated a bit just there. What the RegisterGeneratedFactory() method does, is (approximately):

builder.Register<Shareholding.Factory>(
  (c, p) =>
    (symbol, quantity) =>
      c.Resolve<Shareholding>(new Parameter("symbol", symbol), new Parameter("quantity", quantity)))
  .ContainerScoped();

Now that is a mouthful of lambda! Autofac 1.1 uses Linq to translate the parameters of the Shareholding.Factory delegate, symbol and quantity into named parameters that can be fed to the container's Shareholding constructor call.

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.

Closing note - you need a pretty flexible ORM, like NHibernate before you'll get very far trying to pull tricks like this with your domain model ;)

15 comments.

Nicholas Blumhardt

The Diamond Age

Posted by Nicholas Blumhardt | February 29, 2008 18:12

I don't want to stray too far from the usually dry technical content of this blog :) but The Diamond Age by Neal Stephenson deserves an exception.

His earlier novel, Snow Crash, is something of a cyberpunk masterpiece set in the virtual world of tomorrow. Its about computers, an ancient Sumerian god, linguistics and a katana-wielding pizza delivery driver. It wasn't a hard sell.

The Diamond Age, on the other hand, is about nanotechnology, and well, a girl's schoolbook... As much as I loved Snow Crash it has taken me years to get around to reading it.

And, it is brilliant. The world of The Diamond Age is so easily traced back to the world we know today, but in most other respects, especially social ones, eerily foreign.

Advanced nanotechnology as imagined by Stephenson changes the way people work, interact and think, even more than the Internet has changed us.

Get your copy fresh from a matter compiler (!!!) near you!

0 comments.

Nicholas Blumhardt

SharpDevelop 3.0

Posted by Nicholas Blumhardt | February 25, 2008 08:48

Hi everyone. Just a quick note to share some joy - I recently shelled out for Visual Studio 2008, then, of course, decided to check out the competition. I like it.

SharpDevelop 3.0 has just hit beta 1, and feels like a good solid tool. Unlike Visual Studio, which comes bundled with a lot of very advanced designer-driven functionality, SharpDevelop feels like the product of the more agile mindset driving the project.

I'd gladly trade half of the VS features for integrated code coverage testing like this:

SharpDevelop 3.0 Code Coverage

For this reason alone, SharpDevelop has already found its place in my workflow. The integrated Subversion support is nice too, but of course Tortoise is still the one client to rule them all :)

2 comments.

All Posts

Disclaimer: These articles represent the opinions of the authors and may not match the official position of Ubik Systems Pty. Ltd. Confirmation should be sought on all matters involving professional advice.