文章出處
文章列表
今天在將一個項目遷移至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。循環依賴問題就這么閃亮登場了。
文章列表
全站熱搜