Thursday, April 11, 2024

Dependency Injection Issue for HttpClient

DI issue,  Unable to resolve service for type 'System.String' while attempting to activate 'xxx.Client'."https://stackoverflow.com/questions/69333244/proper-way-to-di-nswag-auto-generated-client/69335191#69335191
<ItemGroup>
<OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp"> <SourceUri>https://localhost:7268/swagger/v1/swagger.json</SourceUri>
<Options>/UseBaseUrl:false /GenerateClientInterfaces:true</Options>
 </OpenApiReference>
 </ItemGroup>

https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?source=recommendations&view=aspnetcore-7.0&tabs=visual-studio

Install-Package Swashbuckle.AspNetCore -Version 6.2.3
1)Create WebAPI with  swagger/OpenAPI
2)Create Web Application, add OpenAPI  service reference
  eg: URL:  https://localhost:7179/swagger/v1/swagger.json
3)From Web Application, create a client call the API
 public List<WeatherForecast> Forecasts { get; set; }  
 public async Task OnGet()
        {
            swaggerClient swaggerClient;
            string baseUrl = "https://localhost:7165/";
            using (var client = new HttpClient())
            {
                swaggerClient = new swaggerClient(baseUrl, client);
                Forecasts =(List < WeatherForecast >)await swaggerClient.GetWeatherForecastAsync();
            }
        }

Blog Archive