Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type ServiceCollection to type 'Autofac.ContainerBuilder' using dotnet core and autofac

I am trying to use autofac in my dotnet core 3.1 project, but I am unable to run project after writing ConfigureContainer inside the startup.cs file.

    public void ConfigureContainer(ContainerBuilder builder)
    {

        var databaseConnectionString = Configuration.GetConnectionString("Database");

        builder.RegisterModule(new MediatorModule());
        builder.RegisterModule(new ApplicationModule(databaseConnectionString));
    }

The error I am getting is :

System.InvalidCastException: Unable to cast object of type
'Microsoft.Extensions.DependencyInjection.ServiceCollection' to type 'Autofac.ContainerBuilder'. at Microsoft.Extensions.Hosting.Internal.ConfigureContainerAdapter`1.ConfigureContainer(HostBuilderContext hostContext, Object containerBuilder) at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider() at Microsoft.Extensions.Hosting.HostBuilder.Build() at Program.Main(String[] args) in C:\src\Program.cs:line 39

like image 379
Benjamin Avatar asked Jan 10 '20 10:01

Benjamin


People also ask

Is Autofac needed in .NET core?

Autofac is the most widely used DI/IoC container for ASP.NET, and it is fully compatible with.NET Core as well. . NET Core has a built-in dependency injection framework that is ready to use. Even though the default DI may provide sufficient functionality, there are several limitations when using it.

What is IServiceCollection in .NET core?

AddScoped(IServiceCollection, Type, Type) Adds a scoped service of the type specified in serviceType with an implementation of the type specified in implementationType to the specified IServiceCollection.


1 Answers

When you configure your host you should call UseServiceProviderFactory(new AutofacServiceProviderFactory())

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();
}

Without this, .net core will create a ServiceCollection instead of a ContainerBuilder and an InvalidCastException will be thrown.

like image 141
Cyril Durand Avatar answered Sep 20 '22 16:09

Cyril Durand