System.AggregateException:“某些服务无法构建”在我的 ASP.net core 中

问题描述 投票:0回答:4

我有一个模型:

public class Checkout
{
    public string CheckoutId { get; set; }

    public List<CheckoutItem> CheckoutItems { get; set; }

}

我正在尝试向对象添加方法,同时尊重 POCO。所以我添加了一个存储库:

    public class CheckoutRepository : ICheckoutRepository
    {
        private readonly AppDbContext _appDbContext;
        private readonly Checkout _checkout;

        public CheckoutRepository(AppDbContext appDbContext, Checkout checkout)
        {
            _appDbContext = appDbContext;
            _checkout = checkout;

        }

        public void AddItem(unitItem item, int amount)
        {
              //Removed for brevity 
        }

        public void ClearCheckout()
        {
           //Details removed for brevity
        }

        public Checkout GetCart(IServiceProvider serviceProvider)
        {   
          //Details removed for brevity
        }

        public List<CheckoutItem> GetCheckoutItems()
        {
            //Details removed for brevity
        }

        public decimal GetCheckoutTotal()
        {
           //Details removed for brevity
        }

        public decimal RemoveItem(unitItem item)
        {
           //Details removed for brevity
        }

以及存储库的接口

public interface ICheckoutRepository
    {
         Checkout GetCart(IServiceProvider serviceProvider);

        void AddItem(unitItem item, int amount);

        decimal RemoveItem(unitItem item);

        List<CheckoutItem> GetCheckoutItems();

        void ClearCheckout();

        decimal GetCheckoutTotal();
    }

我当然将其添加到启动文件中。

services.AddTransient<ICheckoutRepository, CheckoutRepository>();

但是当我运行应用程序时,我收到错误

System.AggregateException:“某些服务无法 已建成'

还有 2 个内部例外

1:

InvalidOperationException:验证服务时出错 描述符'ServiceType:BataCMS.Data.Interfaces.ICheckoutRepository 生命周期:瞬态实现类型: BataCMS.Data.Repositories.CheckoutRepository':无法解析 尝试时类型“BataCMS.Data.Models.Checkout”的服务 激活“BataCMS.Data.Repositories.CheckoutRepository”。

还有2:

InvalidOperationException:无法解析类型的服务 尝试激活时出现“BataCMS.Data.Models.Checkout” 'BataCMS.Data.Repositories.CheckoutRepository'

确实可以对这个问题有所了解。

c# asp.net-core asp.net-core-mvc
4个回答
26
投票

当您查看

CheckoutRepository
构造函数时,您会发现您正在注入
Checkout
类的实例。 ASP.NET 不知道在哪里搜索要注入的该类的实例,因此您必须在 DI 容器中注册它。

将其添加到您的启动文件中:

services.AddTransient<Checkout>(new Checkout());

这是一种有点不同的注册类型。您不依赖于抽象,而是依赖于

Checkout
类的具体实现。我已将默认的无参数构造函数传递给上面的示例,但您可以将任何其他构造函数传递给它,或者(取决于抽象)只需创建
ICheckout
接口并注册,就像注册
ICheckoutRepository
一样:

services.AddTransient<ICheckout, Checkout>();

有关 DI 的更多信息可以在此处

找到

我还在这个视频

中探索了它的实用方法

2
投票

也许你失踪了?

services.AddTransient<ICheckout, Checkout>();

希望我有帮助。


1
投票

这是因为我在 IRepo 中声明为

IEnumerable
并从 repo 传递了一个列表。

修复此问题解决了我的问题


0
投票

当 Context 类使用加深注入时也会发生这种类型错误

© www.soinside.com 2019 - 2024. All rights reserved.