While running the .Net Core 2.0 API endpoint getting below error.

A suitable constructor for type 'RestDataService' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

 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;
        }
........

And my startup class is something like this :

  // 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);

Any suggestions, to get rid of this? constructor is already public and all the parameters are registered in startup file

2 Answers

0
t-prisar On

You have to define which concrete class of interface you want to use for IRestDataService. So, define like this.

services.AddTransient<IRestDataService, RestDataService>();

Remove static keyword before AppConfiguration.

private readonly AppConfiguration _configuration;
0
Tao Zhou On

For AddHttpClient, you need to provide HttpClient parameter for RestDataService. And, you need to register 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>();