How to register and get all instances that implement an interface using Autofac

I’ve just started using Autofac, where I’ve previously used Ninject and StructureMap.

UPDATE (09/06/2001): Although this post is about registering all instances that implement a specific interface, my reason for doing so was to create a bootstrapper task. I’ve recently found AutoFac has an IStartable interface which basically does the same thing.

I have an interface called IBootStrapperTask that looks like this:

public interface IBootStrapperTask
    void Execute();

I then have several tasks that implement this interface, which I want to get and run when my application starts. First I need to register all types that use this interface, which I don’t want to do by automatically registering all types. I can do this like so:

var builder = new ContainerBuilder();

builder.RegisterAssemblyTypes(Assembly.Load("MyAssesmbly")).Where(t => typeof(IBootStrapperTask).IsAssignableFrom(t)).InstancePerLifetimeScope().AsImplementedInterfaces();

From what I can tell you can only do this on a per assembly basis. Now I have all my types registered I can get and execute them all:

var container = builder.Build();

var tasks = container.Resolve<IEnumerable<IBootStrapperTask>>();
foreach (var task in tasks)
Posted on by Joe in C#

3 Responses to How to register and get all instances that implement an interface using Autofac

  1. Saeed Neamati

    LINQ for sure has changed the way .NET developers code. Thank you for this post. Though I’m against using other libraries like Autofac.

  2. Joe

    This post has nothing to do with LINQ. Why would you be against libraries that help provide a loosely coupled architecture. Do you even understand what this post is about?

  3. Richard

    Exactly what I was searching for, thank you !

Add a Comment