Before .NET 6 Minimal API’s you had 2 places where you had to apply some changes to replace the built-in IoC container with Autofac.
First in your Program.cs file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Program | |
{ | |
public static void Main(string[] args) | |
=> CreateHostBuilder(args).Build().Run(); | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.UseStartup<Startup>(); | |
}); | |
} |
And second in your Startup.cs file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Startup | |
{ | |
public void ConfigureContainer(ContainerBuilder containerBuilder) | |
{ | |
// Add your Autofac DI registrations here | |
} | |
} |
But what should you do when using .NET 6 Minimal API’s? In that case your Startup.cs file is gone.
You still need to apply the same 2 steps but this time directly on the Host property of the WebApplicationBuilder:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var builder = WebApplication.CreateBuilder(args); | |
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); | |
builder.Host.ConfigureContainer<ContainerBuilder>(builder => | |
{ | |
// Add your Autofac DI registrations here | |
}); |
Remark: I assume that the process is quite similar for other 3th party IoC containers.