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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With