在.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。循环依赖问题就这么闪亮登场了。

posted @ 2016-12-28 18:18  dudu  阅读(3219)  评论(4编辑  收藏  举报