尚未注册类型“IServiceProviderFactory[Autofac.ContainerBuilder]”的服务

Ham*_*med 3 c# autofac entity-framework-core asp.net-core

当运行以下命令添加数据库迁移脚本时,出现以下错误:

dotnet ef migrations add InitialCreate -v -o .\Migrations\ --context MyContext
Run Code Online (Sandbox Code Playgroud)

访问 Microsoft.Extensions.Hosting 服务时出错。在没有应用程序服务提供商的情况下继续。错误:未注册类型“Microsoft.Extensions.DependencyInjection.IServiceProviderFactory`1[Autofac.ContainerBuilder]”的服务。

我已遵循文档。该类Startup的实现如下:

dotnet ef migrations add InitialCreate -v -o .\Migrations\ --context MyContext
Run Code Online (Sandbox Code Playgroud)

有什么想法导致错误的原因以及如何修复它吗?

版本:

<TargetFramework>netcoreapp3.1</TargetFramework>
<PackageReference Include="Autofac" Version="4.9.4" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="5.0.1" />
Run Code Online (Sandbox Code Playgroud)

小智 6

您必须在 Program.cs 中配置 Autofac:

var hostBuilder = new WebHostBuilder()
            .UseContentRoot(Path.GetDirectoryName(path))
            .ConfigureServices(services => services.AddAutofac())
            .ConfigureAppConfiguration(cb =>
            {
                cb.AddJsonFile("appsettings.json", optional: false).AddEnvironmentVariables();
            }).UseStartup<Startup>();
Run Code Online (Sandbox Code Playgroud)

或者

 return Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureAppConfiguration((builderContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {   
                webBuilder.UseStartup<Startup>();
            });
Run Code Online (Sandbox Code Playgroud)