简介
当我们遇到这样的报错时,我们可能第一反应就是,怎么会这样,我应该怎么才能解决掉这个问题
System.InvalidOperationException: A circular dependency was detected for the service of type 'ML.Xncf.Admin.Services.SubscribeProductsService'. ML.Xncf.Admin.Services.SubscribeProductsService -> ML.Xncf.Admin.Services.CategoryService -> ML.Xncf.Admin.Services.SubscribeProductsService at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain.CheckCircularDependency(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.<>c__DisplayClass7_0.<GetCallSite>b__0(Type type) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(Type serviceType, CallSiteChain callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
步骤
1.读懂这个问题
2.分析问题可能产生的原因
3.根据提供的报错信息去顺藤摸瓜
4.尝试修改
5.重复3,4步骤
案例
1.读懂问题
A circular dependency was detected for the service of type 'ML.Xncf.Admin.Services.SubscribeProductsService'
译文:检测到类型为的服务的循环依赖项
2.分析问题
当我们看到这样的字样的时候,我们肯定知道肯定是循环依赖了,但就是不知道发生在哪里,紧接着我们再看后面
ML.Xncf.Admin.Services.SubscribeProductsService -> ML.Xncf.Admin.Services.CategoryService -> ML.Xncf.Admin.Services.SubscribeProductsService
我们发现,提示告诉我们是:
SubscribeProductsService ,CategoryService,SubscribeProductsService
这样的循环顺序
3.顺藤摸瓜
在文件SubscribeProductsService.cs中,我们找到了这样的引用
private readonly CategoryService categoryService; public SubscribeProductsService(IRepositoryBase<SubscribeProducts> repo, IServiceProvider serviceProvider, CategoryService categoryService) : base(repo, serviceProvider) { this.categoryService = categoryService; }
在文件CategoryService.cs中,我们找到了这样的引用
private readonly SubscribeProductsService subscribeProductsService; public CategoryService(IRepositoryBase<Category> repo, IServiceProvider serviceProvider,SubscribeProductsService subscribeProductsService) : base(repo, serviceProvider) { this.subscribeProductsService = subscribeProductsService; }
问题比较明朗了,问题就是,我引用了你,你又引用了我,那系统没办法知道到底是该谁引用谁,然后就傻傻分不清楚了
4.尝试修改
我们将SubscribeProductsService.cs文件中的CategoryService直接删掉,再去尝试看看结果
就可以看到,我们已经成功的解决了这个问题,由此我们可以知道,类似的问题,我们编写的时候需要注意排查
养成一个好的习惯,如果仍未解决掉,请重试3,4的顺序来进行调试
希望大家写出无Bug的项目
欢迎大家找我交流