运行.Net Core 2.0 API端点低于错误时。
找不到适合类型'RestDataService'的构造函数。确保类型是具体的,并为公共构造函数的所有参数注册服务。
public partial class RestDataService : IRestDataService
{
private static HttpClient _client;
private static AppConfiguration _configuration;
private const short MaxRetryAttempts = 3;
private const short TimeSpanToWait = 2;
public RestDataService(AppConfiguration configuration)
{
_client = configuration.HttpClient;
_configuration = configuration;
}
........
我的启动类是这样的:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var config = new AppConfiguration
{
Environment = Configuration["environment"],
};
services.AddMvc().AddJsonOptions(o => o.SerializerSettings.NullValueHandling = NullValueHandling.Include);
services.AddMemoryCache();
services.AddCors();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddSingleton(Configuration);
services.AddSingleton(config);
services.AddLogging();
services.AddTransient<IRestDataService, RestDataService>();
services.AddHttpClient<IRestDataService, RestDataService>()
.AddPolicyHandler(request => request.Method == HttpMethod.Get ? retryPolicy : noOp);
有什么建议要摆脱这个?构造函数已经公开,并且所有参数都已在启动文件中注册
答案 0 :(得分:4)
我收到错误“找不到适合类型 '
答案 1 :(得分:0)
您必须定义要用于IRestDataService的接口的具体类。所以,这样定义。
services.AddTransient<IRestDataService, RestDataService>();
在AppConfiguration之前删除静态关键字。
private readonly AppConfiguration _configuration;
答案 2 :(得分:0)
对于AddHttpClient
,您需要为HttpClient
提供RestDataService
参数。并且,您需要注册AppConfiguration
。
RestDataService
public class RestDataService: IRestDataService
{
private static HttpClient _client;
private static AppConfiguration _configuration;
private const short MaxRetryAttempts = 3;
private const short TimeSpanToWait = 2;
public RestDataService(AppConfiguration configuration
, HttpClient client)
{
_client = configuration.HttpClient;
_configuration = configuration;
}
}
Startup.cs
var config = new AppConfiguration
{
Environment = Configuration["environment"],
};
services.AddSingleton(typeof(AppConfiguration), config);
services.AddHttpClient<IRestDataService, RestDataService>();
答案 3 :(得分:0)
我刚刚遇到了这个问题,因为我不小心将 HttpClient
注册到了 interface
。
public void ConfigureServices(IServiceCollection services) {
// !! Wrong, this is done automatically by AddHttpClient<IMyService, MyService>()
services.AddTransient<IMyService, MyService>();
// !! There is no suitable constructor for IMyService, since it is an interface.
services.AddHttpClient<IMyService>();
// Instead, let AddHttpClient manage your service's lifetime,
// and tell it the implementation.
// It is registered with a Transient lifetime as described below.
services.AddHttpClient<IMyService, MyService>();
}
<块引用>
在 ConfigureServices 方法中定义类型化客户端时,类型化服务注册到瞬态范围。这意味着每次需要时,DI 容器都会创建一个新实例。发生这种情况的原因是 HttpClient 实例被注入到类型化的客户端实例中。该 HttpClient 实例的生命周期很短,以便 HttpClientFactory 可以确保释放和回收底层处理程序(和连接)。