首页 > 解决方案 > 向 Scrutor 注册依赖

问题描述

我有3个项目

1 带控制器

2 应用服务

3 带接口

我写了界面

public interface ICheckoutAppService
{
    OrderDto GetOrder();
}

然后在应用服务中实现

 public class CheckoutAppService : ICheckoutAppService
{
    public OrderDto GetOrder()
    {
        var checkout = new OrderDto
        {
            Amount = 50,
            ServiceType = "ecom",
            BillRefNo = "BIZ-TEST-PR05004",
            CurrencyCode = "SGD",
            Payee = "{{payee_payeeliquid}}",
            OrderId = "Order_11121314",
            OrderItems = new List<OrderItemDto>
            {
                new()
                {
                    ItemName = "Dell Laptop",
                    ItemNumber = "1",
                    ItemUnitPrice = 1000,
                    OrderQuantity = 1
                },
                new()
                {
                    ItemName = "Dell Monitor",
                    ItemNumber = "1",
                    ItemUnitPrice = 500,
                    OrderQuantity = 1
                }
            }
        };

        return checkout;
    }

然后我在第一个项目中从控制器调用它,就像这样

[Route("api/[controller]")]
public class CustomersController : Controller
{
    private readonly ICheckoutAppService _checkoutAppService;

    public CustomersController(ICheckoutAppService checkoutAppService)
    {
        _checkoutAppService = checkoutAppService;
    }

    [HttpGet]
    public OrderDto Get()
    {
        try
        {
           return _checkoutAppService.GetOrder();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

我像这样通过 Scrutor 在启动时注册接口

services.Scan(scan =>
            scan.FromAssemblyOf<ICheckoutAppService>()
                .AddClasses()
                .AsMatchingInterface());

并得到这个错误

System.InvalidOperationException:尝试激活“CheckoutAPI.Controllers.CustomersController”时无法解析“TestTaskShared.Interfaces.ICheckoutAppService”类型的服务。

我该如何解决这个问题?

标签: .netasp.net-coredependency-injectionscrutor

解决方案


是否ICheckoutAppServiceCheckoutAppService在同一个程序集中?

如果不是,您当前的扫描仅使用引用接口的项目,并且不会找到该类。我假设该课程在Appservices 项目中。

您将需要参考该项目,以便审查员知道在哪里寻找实施。

考虑改变扫描方法

services.Scan(scan =>
        scan.FromAssemblyOf<CheckoutAppService>()
            .AddClasses()
            .AsMatchingInterface());

以上将添加Appservices项目中的类作为其匹配的接口。并且由于该Appservices项目会引用该interfaces项目,因此 scutor 将知道如何找到所需的接口


推荐阅读