Implementing Autofac in multiple applications and libraries

Suwarno Ong
1 min readNov 5, 2019

--

First of all, what is Autofac?

Autofac is the advance Inversion of Control container for .NET core. It supports registering the components in various component lifespan, register through assembly scanning, inject the instance through constructor/property/method, and flexible module system.

In here, we will be touching the Autofac module for cross projects scenario.

Let’s say we have 2 apps (web API and console) which both of them are using a class library named CoreLib.

In CoreLib project, we will define a class inherits from Autofac.Module as follows:

public class CoreLibModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<ComponentUtil>().As<IComponentUtil>().SingleInstance();
}
}

In CoreLibModule, it will register ComponentUtil as a singleton. This ComponentUtil will be used by both web API and console app.

In the web API, we will register the above dependency in the Startup.cs using RegisterModule.

public class Startup
{
...
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule<CoreLibModule>();
}
...
}

In the console app, we will register it in the Program.cs almost in the same way as above.

using Autofac;class Program
{
private static IContainer Container { get; set; }
static void Main(string[] args)
{
Container = ConfigureDependencies();
}
private static IContainer ConfigureDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterModule<CoreLibModule>();
return builder.build();
}
}

In this case, we are ready to inject IComponentUtil in the constructor class in both web API and console app.

--

--

No responses yet