尚未注册类型为'IServiceProviderFactory[Autofac.ContainerBuilder]'的服务

No service for type #39;IServiceProviderFactory[Autofac.ContainerBuilder]#39; has been registered(尚未注册类型为#39;IServiceProviderFactory[Autofac.ContainerBuilder]#39;的服务)

本文介绍了尚未注册类型为'IServiceProviderFactory[Autofac.ContainerBuilder]'的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

dotnet ef migrations add InitialCreate -v -o .Migrations --context MyContext
访问Microsoft.Extensions.Hosting服务时出错。在没有应用服务提供商的情况下继续。错误:尚未注册类型为‘Microsoft.Extensions.DependencyInjection.IServiceProviderFactory`1[Autofac.ContainerBuilder]’的服务。

我遵循了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" />

推荐答案

ConfigureServices替换为:

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

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

    var container = new ContainerBuilder();
    container.Populate(services);
    return new AutofacServiceProvider(container.Build());
}

请注意,这与Autofac's docs suggest完全矛盾,但它是解决问题所必需的。

将服务添加到集合。不要生成或返回任何IServiceProvider,否则将不会调用ConfigureContainer方法。

这篇关于尚未注册类型为&#39;IServiceProviderFactory[Autofac.ContainerBuilder]&#39;的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:尚未注册类型为&#39;IServiceProviderFactory[Autofac.ContainerBuilder]&#39;的服务

基础教程推荐