ASP.NET Core Pitfalls – Returning a Custom Service Provider from ConfigureServices
In pre-3.1 versions of ASP.NET Core, you could return your own service provider (AutoFac, Ninject, etc) by returning some IServiceProvider-implementing class from the ConfigureServices method. This is no longer supporting, and having code like this results in an NotSupportedException being thrown at startup:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//something
return myCustomServiceProvider;
}
The way to do it now is by registering a service provider factory at bootstrap, something like this:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new CustomServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
A custom service provider factory must implement IServiceProviderFactory<T>, for an example, you can see Autfac’s implementation: https://github.com/autofac/Autofac.Extensions.DependencyInjection/blob/develop/src/Autofac.Extensions.DependencyInjection/AutofacServiceProviderFactory.cs and https://github.com/autofac/Autofac.Extensions.DependencyInjection/blob/develop/src/Autofac.Extensions.DependencyInjection/AutofacChildLifetimeScopeServiceProviderFactory.cs.