gpt4 book ai didi

c# - 没有注册类型 'IServiceProviderFactory[Autofac.ContainerBuilder]' 的服务

转载 作者:行者123 更新时间:2023-12-04 12:40:46 27 4
gpt4 key购买 nike

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

dotnet ef migrations add InitialCreate -v -o .\Migrations\ --context MyContext

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: No service for type 'Microsoft.Extensions.DependencyInjection.IServiceProviderFactory`1[Autofac.ContainerBuilder]' has been registered.

我关注了this文档。 Startup 类的实现如下:

public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
WebHostingEnvironment = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

services.AddCustomDbContext(Configuration);
services.AddOptions();
}

public void ConfigureContainer(ContainerBuilder builder)
{ }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseMvc();
ConfigureEventBus(app);
}
}

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

版本:

<TargetFramework>netcoreapp3.1</TargetFramework>
<PackageReference Include="Autofac" Version="4.9.4" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="5.0.1" />

最佳答案

你必须在 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>();

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

关于c# - 没有注册类型 'IServiceProviderFactory[Autofac.ContainerBuilder]' 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59571014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com