Simple Autofac Bootstrapping Example

Couple days ago, I was working on a project that needs to be initialized with some external parameters before it’s composition root ready. Generally, we set the IoC Container when application starts once. But what if we need some services before setting the IoC Container. For some IoC libraries this can be a big pain. Fortunately Autofac solves it with container update operation.

I just created a simple application to explain the idea. It’s very simple actually. By using a flag, we apply Build or Update operation to the given Container.

Here is the example:

Here is our simple Bootstrapper class. There is a simple IsBuilded flag setted by SetAutofacContainer method.

And in the usage of Bootstrapper class, first we need to Initialize a builder to build a container. After we done with registration of objects, we set the container by using SetAutofacContainer method. Then we can resolve registered types by using our Container object or custom written GetService method. Secondly, for moving on with regular IoC registering progress, we reset the Bootstrapper.ContainerBuilder object with InitializeBuilder method. Last, we set new registrations and call SetAutofacContainer method again.

And here is the example project.

That’s it! Hope you liked this simple trick.

I am csharp developer, mathematics graduated, visionary coder, tennis player, bad english speaker, blog reader, blog writer, and very lazy person. I will be sharing my personal thoughts, experiences, hobbies that I'd like to do and different news that takes my interest as a simple, regular person. Sometimes in English, sometimes in Turkish.
  • Timestretchin

    Great example – many thanks for posting it.