Подходящий конструктор для типа RestDataService не может быть найден - PullRequest
1 голос
/ 11 мая 2019

При запуске конечной точки API .Net Core 2.0 ошибка ниже.

Не удалось найти подходящий конструктор для типа 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);

Любые предложения, чтобы избавитьсяэтого?Конструктор уже общедоступен, и все параметры зарегистрированы в файле запуска

Ответы [ 2 ]

0 голосов
/ 13 мая 2019

Для AddHttpClient необходимо предоставить параметр HttpClient для RestDataService.И вам необходимо зарегистрироваться AppConfiguration.

  1. 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;
        }
    }
    
  2. Startup.cs

    var config = new AppConfiguration
    {
        Environment = Configuration["environment"],
    };
    
    services.AddSingleton(typeof(AppConfiguration), config);
    services.AddHttpClient<IRestDataService, RestDataService>();
    
0 голосов
/ 11 мая 2019

Вы должны определить, какой конкретный класс интерфейса вы хотите использовать для IRestDataService. Итак, определите как это.

services.AddTransient<IRestDataService, RestDataService>();

Удалить статическое ключевое слово перед AppConfiguration.

private readonly AppConfiguration _configuration;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...