所以我使用DI在控制器中注入了服务。
Startup.cs
我犯了个错误
IMyService' is a type which is not valid in a given context
.
这是我的密码:
namespace MyDemoApp.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(IProductService, ProductService);
}
}
}
ProductService
namespace MyDemoApp.Services
{
public class ProductService : IProductService
{
private readonly HttpClient _HttpClient;
public ProductService(HttpClient HttpClient)
{
_HttpClient = HttpClient;
}
public async Task<string> RequestProductUrlFromAnotherAPI(CancellationToken cancellationToken)
{
var prodUrl = "https://......";
var response = await _HttpClient.Get<ProductDto>(prodUrl, cancellationToken);
if(response!= null && response.Success && response.Data != null && !string.IsNullOrWhiteSpace(response.Data))
{
return response.Data;
}
else
{
throw new ArgumentException("Data is not retrieved.");
}
}
}
}