繁体   English   中英

我该如何处理这个依赖注入错误?

[英]how do i deal with this dependency injection error?

我正在使用全栈创建一个网站,但我的一个控制器无法注入接口,并且从浏览器中收到以下错误:

InvalidOperationException:尝试激活“SolarCoffee.Web.Controllers.ProductController”时无法解析“SolarCoffee.Services.Product.IProductService”类型的服务。

我的代码如下//启动

using Microsoft.EntityFrameworkCore;
using SolarCoffee.Data;
using Npgsql.EntityFrameworkCore;
using Stripe;
using SolarCoffee.Services.Product;
namespace SolarCoffee.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get;  }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddControllers();
        services.AddDbContext<SolarDbContext>(opts =>
        
            //opts.UseNpgsql("solar.dev=ConnectionStrings:DefaultConnection")
        //);
        {
            opts.EnableDetailedErrors();
            opts.UseNpgsql(Configuration.GetConnectionString("Data Source = solar.dev"));
        });
        services.AddScoped<IProductService, Services.Product.ProductService>();
        
    }

    //this method gets called by the runtime. use this method to configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization(); 

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

}

}

//控制器

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SolarCoffee.Data.Models;
using SolarCoffee.Services.Product;

namespace SolarCoffee.Web.Controllers
{
    [ApiController]
    public class ProductController : ControllerBase
    {
    private readonly ILogger<ProductController> _logger;
    private readonly IProductService _productService;

    [ActivatorUtilitiesConstructor]
    public ProductController(ILogger<ProductController> logger, IProductService productService)
    {
        _logger = logger;
        _productService = productService;
    }

    [HttpGet("api/product")]
    public ActionResult GetProduct()
    {
        _logger.LogInformation("Getting all products");
        var products = _productService.GetAllProducts();
        return Ok(products);
    }
}

}

//服务接口

using System.Collections.Generic;

namespace SolarCoffee.Services.Product
{
    public interface IProductService
    {
        List<Data.Models.Product> GetAllProducts();
        Data.Models.Product GetProductById(int id);
        ServiceResponce<Data.Models.Product> CreateProduct(Data.Models.Product product);
        ServiceResponce<Data.Models.Product> ArchiveProduct(int id);
    }
}

//接口实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SolarCoffee.Data;
using SolarCoffee.Data.Models;
using SolarCoffee.Services.Product;

namespace SolarCoffee.Services.Product
{
public class ProductService : IProductService
{
    private readonly SolarDbContext _db;

    public ProductService(SolarDbContext dbContext)
    {
        _db = dbContext;
    }


    /// <summary>
    /// Archives a product by setting setting boolean IsArchived to true
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public ServiceResponce<Data.Models.Product> ArchiveProduct(int id)
    {
        try
        {
            var product = _db.Products.Find(id);
            product.IsArchived = true;
            _db.SaveChanges();

            return new ServiceResponce<Data.Models.Product>
            {
                Data = product,
                Time = DateTime.UtcNow,
                Message = "Archived product",
                IsSuccess = true
            };
        }
         catch (Exception e)
        {
            return new ServiceResponce<Data.Models.Product>
            {
                Data = null,
                Time = DateTime.UtcNow,
                Message = e.StackTrace,
                IsSuccess = false
            };
        }
    }

    /// <summary>
    /// Adds a new product by primary key
    /// </summary>
    /// <param name="product"></param>
    /// <returns></returns>
    public ServiceResponce<Data.Models.Product> CreateProduct(Data.Models.Product product)
    {
        try
        {
            _db.Products.Add(product);

            var newInventory = new ProductInventory
            {
                Product = product,
                QuantityOnHand = 0,
                IdealQuantity = 10,
            };

            _db.ProductInventries.Add(newInventory);

            _db.SaveChanges();

            return new ServiceResponce<Data.Models.Product>
            {
                Data = product,
                Time = DateTime.UtcNow,
                Message = "Saved new product",
                IsSuccess = true
            };
        }
   
        catch (Exception ex)
        {
            return new ServiceResponce<Data.Models.Product>
            {
                Data = product,
                Time = DateTime.UtcNow,
                Message = "Error saving new product",
                IsSuccess = true
            };
        }
      
    }

    /// <summary>
    /// Retrives all products from the database
    /// </summary>
    /// <returns></returns>
    public List<Data.Models.Product> GetAllProducts()
    {
        return _db.Products.ToList();
    }

    /// <summary>
    /// Retrieves a Product from the database by primary key
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public Data.Models.Product GetProductById(int id)
    {
        return _db.Products.Find(id);
    }
}

}

我看不到哪里弄错了

所以问题出在我的 sdk 上。 一些 nu-get 包与我使用的 .net6.0 不兼容,所以我降级到 3.1 并且错误消失了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM