代码之家  ›  专栏  ›  技术社区  ›  Roxy'Pro

.net核心依赖注入“IMyService”是在给定上下文中无效的类型

  •  0
  • Roxy'Pro  · 技术社区  · 5 年前

    所以我使用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.");
                }
            }
        }
    }
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Guru Stron    5 年前

    您应该使用:

    services.AddScoped(typeof(IProductService), typeof(ProductService));
    

    services.AddScoped<IProductService, ProductService>();
    

    第一个是 overload System.Type 班级, typeof 操作员获得 类型名的实例。

    第二个是 overload generic type parameters (另请参见 generics ).

    推荐文章