Convention-based part registration available in a new MEF preview!

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 convention-driven approach used by IoC containers.

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.

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.

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:

var builder = new RegistrationBuilder();
builder.ForTypesDerivedFrom<Controller>()
    .Export()
    .SetCreationPolicy(CreationPolicy.NonShared);

When wired up to a MEF catalog, these simple conventions will read a part like:

public class HomeController :  Controller
{
    public HomeController(/* Dependencies here */) {}
    public ActionResult Index() {}
}

As:

[Export, PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController :  Controller
{
    [ImportingConstructor]
    public HomeController(/* Dependencies here */) {}
    public ActionResult Index() {}
}

RegistrationBuilder has more than a few tricks up its sleeve, and we expect to write a lot more about it on the BCL team blog in the coming weeks. For now, you can read about the new release, or even better, download the preview source and binaries from CodePlex.

Autofac 2.5 Released

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’re up and running!) For some tips on getting started see Brendan Kowitz’s notes.

The new release is highly-compatible with Autofac 2.4 (best used with the VS2010 compiler when targeting .NET 3.5.)

Included changes are:

  • Issue 329 – types are filtered by compatibilty before invoking key mapping functions when scanning assemblies
  • RegisterAssemblyTypes(...).WithMetadataFrom<T>() simplifies extraction of metadata from attribute properties
  • Module.ThisAssembly simplifies implementation of modules that scan their own assembly
  • Issue 333 – enable RegisterAssemblyTypes(...).PreserveExistingDefaults()
  • Windows Phone 7 and 7.1 support
  • Issue 312 – allow ContainerBuilder.Update() on the ComponentRegistry of any
    ILifetimeScope without affecting the parent scope
  • Issue 327 – allow autowiring of enum properties
  • Issue 319 – support list and dictionary literals in XML configuration
  • Issue 330 – corrections to generic type constraint checking where the constraint type is an interface
  • Issue 331 – fix build warnings and runtime issues using Moq integration
  • Introduced ContainerBuildOptions to control invocation of IStartable.Start() under unit tests
  • Container.Empty is now a property rather than a field (protection from inadvertent updates
  • Removed broken/obsolete examples from source tree (better examples are available elsewhere online)
  • Host configuration features for AutofacHostFactory in WCF integration
  • ComponentRegistry.Register() is now safe for use under multiple threads
  • Issue 227 – breaking change additional options (and enum rather than boolean parameter) for PropertiesAutowired()
  • Additional web abstractions are now registered by the MVC3 AutofacWebTypesModule
  • Issue 311 – fixed potential lifetime issues when injecting into MVC filter attributes
  • Tightened up behavior when correct constructor to use under reflection activator is ambiguous (now throws rather than choosing nondeterministically)
  • Issue 309 – fixed some issues in TypeExtensions.IsClosedTypeOf()
  • Improved exception messages

Many thanks to the Autofac project team and collaborators across the web for making this release happen!

Designing a Short Course on IoC: Day 5

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 – Fundamentals – is finished. I’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.

The layout for the remainder of the day still needs work, so I’d better get stuck into it! Those who’ve already signed up, I’ll see you soon – if you haven’t put your name down yet for either Brisbane, Sydney or Melbourne, this is probably the last reminder you’ll get from me.

Designing a Short Course on IoC: Day 4

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 view of the composition process as the application is built. The information it provides is great – often revealing little issues that would otherwise go unnoticed – but the usability leaves me deeply unsatisfied. Still, it is a start, and by chipping away at it things are improving. Just having a simple view of component details is an improvement:

Whitebox component detail view

Today I’m concentrating on the flow of the day. I still have some questions to answer around the introductory session – 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 “you’re going to use IoC – here’s how to do it” I think the practical side of the Dev Day will be emphasised.

Designing a Short Course on IoC: Day 3

Is it just me, or am I slowing down? Yesterday was a busy day of programming, but there’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 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.

Up and running, we have:

  • A basic MVC3 app layout
  • IoC set up to create controllers
  • Data access with NHibernate
  • Transaction management integrated with MVC
  • Logging with the venerable log4net
  • A skeleton for ‘pick-me-up’ domain events

It is the last item that I’ll be working on in depth today. ‘Pick-me-up’ domain events integrate domain models with external services in a way that plays better with IoC than the thread-static DomainEvents.Raise() pattern commonly seen elsewhere.

Dispatching events to handlers is also a good example of the ‘generic handler’ pattern that’s very widely used, and registering handlers will provide some further examples for convention-based/scanning registration.

To complete the day I’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 “Resources and Units of Work” session. That leaves tomorrow and Friday for more detailed work on slides, some code samples for the “Containers” session, and some reworking of the example to fit into the flow of the course.

Designing a Short Course on IoC: Day 2

So, yesterday, a lot of thinking. Today it’s time to start fleshing out some of the things we’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:

  1. Fundamentals
  2. Effective IoC
  3. Resources and Units of Work
  4. Containers and Tooling

Session 1: Fundamentals

First up, we’ll set the theme of the day with some collaborative development. To introduce the vocabulary and concepts of IoC, we’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’ll come back to in our discussion of containers and tooling.

Session 2: Effective IoC

The second session will introduce a ‘real’ IoC container. The focus will be on techniques and features that allow IoC to support large, complex applications in the real world. We’ll touch on all of the typical components of MVC web applications as we migrate from the simple container we built ourselves, but we’ll pay special attention to the integration between IoC and domain models because of the challenges and opportunities they present.

Session 3: Resources and Units of Work

Lifetime, AKA “resource management” can be the toughest aspect of IoC to master. We’ll take an excursion outside of the comfort of the web tier, to develop a thorough understanding of the issues involved and their solutions.

Although it is far from being ready for prime time, Whitebox will be a great way to explore the runtime behaviour of lifetime scenarios, so sometime over the coming week I’ll look at filling remaining gaps there.

Session 4: Containers and Tooling

To round out the day, we’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.

Session 4 will also give us an opportunity to examine debugging and diagnostics issues.

Today

So, what do you think?

Today’s focus for me will be to take a first cut at building the example application. I’m going to leave the ‘simple container’ 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.

Choosing what kind of application to build is tricky. I want attendees to be able to take something away, ideally a sample that isn’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 ‘to-do’ or ‘timesheeting’ application. There’s some high-quality code on the web that might be reused for this purpose (e.g. FunnelWeb) so building something that mimics an existing open source application has advantages.

I’ll update you tomorrow on where things land.

Designing a Short Course on IoC: Day 1

Today’s the start of a really exciting week for me!

I’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 truly blossomed in the .NET world: from its “enterprise Java” roots we’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.

Along the way there have been many difficult questions posed, and I’ve had to ask and answer my share. It can be easy to go wrong with IoC – remember the “sharp tools” analogy of the ALT.NET movement? – especially when finding the right approach to IoC in a new situation can mean finding several wrong ways first!

Last year at TechEd Australia 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 Readify I’m going to be presenting a short course on IoC from the ground, up.

The course will be a full day, with dates in May, 2011 set for:

The unifying theme will be ASP.NET MVC, but don’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’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.

In terms of level of technical difficulty, I hope there will be something for everyone. You’ll get the most out of the day if you’re a confident .NET developer with beginner-to-intermediate experience with IoC, or if you’re an experienced user of IoC looking for broader and deeper perspectives on its use.

This week I’m preparing material for the course, and while I have a fair idea of the ground to cover, I’m interested in your ideas. I’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!

Autofac 2.4.5 Release

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’ll find:

  • Several bug fixes and improved exception messages
  • Travis and Alex have been busy making the Multi-tenant contrib package work better with the new ASP.NET MVC3 integration
  • The awkward but very useful IContainerAwareComponent introduced in 2.4 has been deprecated and morphed into a much friendlier and more useful Startable implementation
  • Autofac now consistently throws DependencyResolutionException (or a subclass) whenever fatal errors occur during composition

Please feel free to drop in and share your experiences on the discussion forum. For help with using Autofac, including new features, the preferred medium is Stack Overflow.

Autofac Project Status Update

Autofac 2.4 Coming Soon

Sometime early in the New Year we’ll be releasing a new version of Autofac.

The star of the show in Autofac 2.4 is a much revamped ASP.NET MVC implementation by Alex Meyer-Gleaves, optimised for use with the MVC3 release. This promises a much quicker, simpler and more robust setup process, finally ridding us of the dependency on an HTTP module (Web.config change) for lifetime control.

Also included in Autofac 2.4 is support for decorators, including some pretty sophisticated coverage of open generic decorator scenarios. In earlier versions of Autofac the very useful Decorator pattern could be a little awkward to implement – I’ll be writing more soon about how Autofac 2.4 tidies this up.

Finally, the new release will continue our recent efforts to improve error messages and bring more consistency and completeness to the APIs introduced in the 2.x series, such as the assembly scanning support. There are no planned breaking changes.

NuGet Packages

Through distribution with ASP.NET MVC3, the NuGet package manager is rapidly gaining traction as the standard way to distribute open source projects for .NET. Thanks to the pioneering efforts of some of the Autofac community there are packages for:

  • Autofac, including its WCF and MEF integrations, for .NET 3.5/4.0 and Silverlight 3/4 (Autofac)
  • Autofac with ASP.NET MVC2 for .NET 3.5/4.0 (Autofac.Mvc2)
  • Autofac with ASP.NET WebForms for .NET 3.5/4.0 (Autofac.Web)

While we expect to fine tune the packages along with the upcoming 2.4 release, you can certainly use NuGet today if you want to use Autofac in your projects.

Open Generics and Autofac 2.3

Autofac 2.3 hit the shelves more than three months ago but as it coincided pretty closely with the birth of our daughter Vera I didn’t write much about it at the time.

One improvement worth mentioning is the much-expanded support for open generic components, contributed by Rikard Pavelic. I answered a recent question on the Autofac mailing list with “it can’t be done” only to find later that the scenario being discussed was already supported. Though fairly unusual, it is an interesting feature so I’ll describe it below, but first the less exotic cases.

Generic Parameter Constraints

C# allows the arguments of a generic type to apply constraints that parameters must match. For example, we might constrain an event handler implementation to a type of event:

interface IEventHandler<in TEvent> {
    void Handle(TEvent @event);
}

In this small example we have an interface that helps us dispatch event objects to handlers. Typically there would be one or more handlers for each event type, most of them specific to the kind of event. We also have a marker interface for events that should trigger some kind of auditing, and a handler that will make this happen.

interface IAuditableEvent { }

class AuditingEventHandler<TEvent> : IEventHandler<TEvent>
        where TEvent : IAuditableEvent {
    void Handle(TEvent @event) {
       // Write an audit record…
    }
}

Note that the handler uses a generic type constraint to select the kind of events it is interested in. Some events will be auditable, others not:

class ItemAddedToCartEvent { }

class CheckoutCompletedEvent : IAuditableEvent { }

The AuditingEventHandler<TEvent> will be registered as an open generic type.

var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(AuditingEventHandler<>))
    .As(typeof(IEventHandler<>));
var container = builder.Build();

Assuming that we’ve registered all of the different event handlers for the above two events, what should happen when we resolve all of the handlers for ItemAddedToCartEvent?

var handlers = container.Resolve<IEnumerable<IEventHandler<ItemAddedToCartEvent>>>();

The AuditingEventHandler<TEvent> component is registered to provide the IEventHandler<TEvent> service, but the generic type constraint doesn’t match. In earlier versions of Autofac, the above line would have raised an exception.

With support for open generic parameter constraints, Autofac will now instantiate only the types whose constraints match, so the handlers collection above would be returned successfully without any attempt to instantiate the AuditingEventHandler<TEvent>.

If instead an auditable event is to be handled, then the auditing handler would be included:

// Succeeds and returns an AuditingEventHandler<CheckoutCompletedEvent>
var handlers = container.Resolve<IEnumerable<IEventHandler<CheckoutCompletedEvent>>>();

Constraint Types

Autofac 2.3 handles all of the generic parameter constraints you’re likely to encounter, including:

  • new()
  • class and struct
  • Base type and implemented interfaces

Parameter Binding Solver

Open generic types are more subtle and complicated to support than they sometimes appear. Take this contrived but not unimaginable example:

class MonoDictionary<T> : IDictionary<T,T> { }

The generic parameter T appears twice in the parameter list of the implemented IDictionary<TKey,TValue>! That means if we register MonoDictionary<T>:

builder.RegisterGeneric(typeof(MonoDictionary<>))
    .As(typeof(IDictionary<,>));

Then we should be able to resolve IDictionary<int,int> but not IDictionary<int,string>. Tricky – but as of version 2.3, Autofac can handle it.

The example we discussed on the Autofac mailing list was something like:

interface IProducer<T> { }

class NullableProducer<T> : IProducer<T?>
    where T : struct { }

The twist here is that the generic component NullableProducer<T> does not parameterise IProducer<T> directly with T, but rather Nullable<T> (abbreviated to T?).

This means that if we resolve IProducer<int?> then NullableProducer<int> should be activated, while resolving IProducer<int> should ignore NullableProducer<T> altogether.

Autofac 2.3 also supports this case, with some terse but surprisingly succinct code. Hopefully this will open up some new, richer generic component possibilities.