After upgrading my ASP.NET Core application to 3.0 I got an error in Startup.cs when I switched to the new HostBuilder:
System.NotSupportedException: 'ConfigureServices returning an System.IServiceProvider isn't supported.'
Letās take a look at my ConfigureServices() method:
public IServiceProvider ConfigureServices(IServiceCollection services) | |
{ | |
// Add services to the collection | |
services.AddOptions(); | |
// create a container-builder and register dependencies | |
var builder = new ContainerBuilder(); | |
builder.RegisterModule(new AutofacModule()); | |
builder.Populate(services); | |
var container = builder.Build(); | |
// this will be used as the service-provider for the application! | |
return new AutofacServiceProvider(container); | |
} |
Inside my ConfigureServices Iām using the Autofac containerbuilder to build up my container and return an AutofacServiceProvider. Therefore I updated the ConfigureServices() method signature to return an IServiceProvider. This worked perfectly in ASP.NET Core 2.x but is not allowed anymore when using the new HostBuilder in ASP.NET Core 3.0.
Time to take a look at the great Autofac documentation for a solution: https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting. Ok, so to fix this we have to change our ConfigureServices() method to no longer return an IService Provider:
public void ConfigureServices(IServiceCollection services) | |
{ | |
// Add services to the collection | |
services.AddOptions(); | |
} |
Then we have to update the program.cs to register our AutofacServiceProvider there:
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
// ASP.NET Core 3.0+: | |
// The UseServiceProviderFactory call attaches the | |
// Autofac provider to the generic hosting mechanism. | |
var host = Host.CreateDefaultBuilder(args) | |
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) | |
.ConfigureWebHostDefaults(webHostBuilder => { | |
webHostBuilder | |
.UseContentRoot(Directory.GetCurrentDirectory()) | |
.UseIISIntegration() | |
.UseStartup<Startup>(); | |
}) | |
.Build(); | |
host.Run(); | |
} | |
} |
As a last step we have to add a ConfigureContainer() method to the Startup.cs where we can configure the containerbuilder instance:
public void ConfigureContainer(ContainerBuilder builder) | |
{ | |
builder.RegisterModule(new AutofacModule()); | |
} |
Remark: We donāt have to build the container ourselves, this is done by the framework for us.