• 在.NET Core中遭遇循环依赖问题"A circular dependency was detected"


    今天在将一个项目迁移至ASP.NET Core的过程中遭遇一个循环依赖问题,错误信息如下:

    A circular dependency was detected for the service of type 'CNBlogs.Application.Interfaces.ITagService'

    一开始以为是项目之间的引用关系引起的,在project.json中找来找去,一无所获。

    后来从构造函数下手,才发现问题所在。

    实现ITagService的类TagService的构造函数是这么定义的:

    public class TagService : ITagService
    {
        private readonly IContentTagsService _contentTagService;
    
        public TagService(IContentTagsService contentTagService)
        {
            _contentTagService = contentTagService;
        }
    }

    这是很标准的通过构造函数依赖注入的定义方式,本身并没有问题。但是我们来看看实现IContentTagsService的类ContentTagsService的构造函数定义:

    public class ContentTagsService : IContentTagsService
    {
        private readonly ITagService _tagService;
    
        public ContentTagsService(ITagService tagService)
        {
            _tagService = tagService;
        }
    }

    TagService实现ITagService,依赖IContentTagsService;ContentTagsService实现IContentTagsService,却又依赖ITagService。循环依赖问题就这么闪亮登场了。

  • 相关阅读:
    [LeetCode] 55. Jump Game 跳跃游戏
    [LeetCode] 163. Missing Ranges 缺失区间
    [LeetCode] 228. Summary Ranges 总结区间
    获取当时时间和日期
    响应式布局设备分界点
    html5shiv.js分析-读源码之javascript系列
    建站模板开源代码
    js 调试问题
    transform使用参考指南
    浏览器版本过低
  • 原文地址:https://www.cnblogs.com/dudu/p/6230506.html
Copyright © 2020-2023  润新知