Web开发:ABP框架中的服务调用原则--避免服务之间的依赖循环问题

一、报错示例

{
  "code": null,
  "message": "An internal error occurred during your request!",
  "details": null,
  "data": {
    "ActivatorChain": "Castle.Proxies.StudentServiceProxy -> Application.TreeSelect.TeacherService -> Application.StudentService"
  },
  "validationErrors": null
}

public class StudentService : ApplicationService,IStudentService
{
    private readonly ITeacherService _teacherService;

    public StudentService(ITeacherService teacherService)
    {
        _teacherService = teacherService;
    }

    public void DoSomethingWithTeacher()
    {
        _teacherService.DoSomething();
    }
}

public class TeacherService : ApplicationService,ITeacherService
{
    private readonly IStudentService _studentService;

    public TeacherService(IStudentService studentService)
    {
        _studentService = studentService;
    }

    public void DoSomething()
    {
        _studentService.DoSomethingWithTeacher();
    }
}

二、报错原因说明

        这犯了循环依赖(Circular Dependency)的错误,即两个高层服务相互注入的错误。这种依赖关系会导致依赖注入容器在实例化对象时解析错误。

三、解决方案

1.提取共同逻辑到底层服务

public class StudentService : ApplicationService,IStudentService
{
    private readonly ICommonService _commonService;

    public StudentService(ICommonService commonService)
    {
        _commonService = commonService;
    }

    public void DoSomethingWithTeacher()
    {
        _commonService.HandleStudentTeacherInteraction();
        Console.WriteLine("Student interacting with teacher.");
    }
}

public class TeacherService : ApplicationService,ITeacherService
{
    private readonly ICommonService _commonService;

    public TeacherService(ICommonService commonService)
    {
        _commonService = commonService;
    }

    public void DoSomething()
    {
        _commonService.HandleStudentTeacherInteraction();
        Console.WriteLine("Teacher interacting with student.");
    }
}

public class CommonService : ApplicationService,ICommonService
{
    public void HandleStudentTeacherInteraction()
    {
        // 执行与学生和老师之间的互动逻辑
        Console.WriteLine("Handling student-teacher interaction.");
    }
}

 2.使用懒加载(亲测有效)

        AI:通过 Lazy<T> 来延迟实例化依赖,避免在创建对象时立即解析所有依赖

public class StudentService : ApplicationService,IStudentService
{
    private readonly Lazy<ITeacherService> _teacherService;

    public StudentService(Lazy<ITeacherService> teacherService)
    {
        _teacherService = teacherService;
    }

    public void DoSomethingWithTeacher()
    {
        var teacherService = _teacherService.Value; // 只有在需要时才会实例化 TeacherService
        teacherService.DoSomething();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值