Unable to resolve service for type '' while attempting to activate 'Controller'

2021-04-03  乐帮网

netcore

描述错误
如果控制器在AddControllersAsServices()之前而不是之后注册,则使用AddControllersAsServices()仅使用控制器注册来解析控制器。 否则,它将尝试使用构造函数进行解析。

重现
以下单个文件程序在.Net 5.0中运行没有错误 

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Host.CreateDefaultBuilder()
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    }).Build().Run();

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient(x => new Controller("Hello World"));
        services.AddControllers().AddControllersAsServices();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

[ApiController]
[Route("/")]
public class Controller : ControllerBase
{
    private readonly string _str;

    public Controller(string str)
    {
        _str = str;
    }

    [HttpGet]
    public string Get() => _str;
}

但是,当我们在ConfigureServices中的各行之间切换顺序时: 

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers().AddControllersAsServices();
        services.AddTransient(x => new Controller("Hello World"));
    }

我们会得到以下的错误:
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Controller Lifetime: Transient ImplementationType: Controller': Unable to resolve service for type 'System.String' while attempting to activate 'Controller'.)'

请注意,在显式调用services.BuildServiceProvider()。GetRequiredService <Controller>()时; 我们成功地构建了Controller。 

希望下面代码对你有帮助

Host.CreateDefaultBuilder()
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    })
    .UseDefaultServiceProvider((context, options) =>
    {
        options.ValidateOnBuild = false;
    })
    .Build()
    .Run();

https://github.com/dotnet/aspnetcore/issues/27959

公众号二维码

关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com

庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。

欧阳修

付款二维码

如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力