You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.Net Core 3.1 GraphQL项目NetCore.AutoRegisterDi依赖注入失败求助

问题分析与解决方案

从错误信息来看,核心问题非常明确:你的DI容器里没有注册ICountryService、ICountryGroupService这些服务的实现类,所以当尝试激活对应的Resolver时,容器找不到依赖的服务实例。

问题根源

看你在AddProjectRepositories里的自动注册逻辑:

.Where(c => c.Name.EndsWith("Persistence"))

你只筛选了名称以Persistence结尾的类,但你的服务类(比如CountryService、DisclaimerService)都是以Service结尾的,完全不在这个筛选范围内,自然不会被自动注册到DI容器里。

另外还要确认Assembly.GetAssembly(typeof(CommonService))是否真的包含了所有的服务类(比如CountryService)——如果CommonService和其他服务类不在同一个程序集里,这个调用会拿错程序集,导致服务类根本没被扫描到。

修复步骤

  1. 修正自动注册的筛选条件
    把筛选规则改成匹配你的服务类命名规则,比如所有以Service结尾的类:

    public static IServiceCollection AddProjectRepositories(this IServiceCollection services) => services
        .RegisterAssemblyPublicNonGenericClasses(Assembly.GetAssembly(typeof(CountryService))) // 换成包含服务类的程序集类型
        .Where(c => c.Name.EndsWith("Service")) // 匹配Service结尾的实现类
        .AsPublicImplementedInterfaces(ServiceLifetime.Scoped);
    

    这里把typeof(CommonService)换成typeof(CountryService)是为了确保拿到正确的程序集——如果你的所有服务类都在同一个程序集里,用其中任意一个服务类的类型来获取程序集都可以。

  2. 验证服务注册情况(可选排查)
    如果还是有问题,可以在ConfigureServices末尾加一段代码,打印所有已注册的服务,确认ICountryService是否存在:

    foreach (var service in services)
    {
        Console.WriteLine($"Service: {service.ServiceType.Name} -> {service.ImplementationType?.Name}");
    }
    

    这样能直观看到哪些服务被注册了,哪些没被注册。

  3. 手动注册测试(快速验证)
    如果你想快速确认问题,可以先手动注册一个服务试试:

    services.AddScoped<ICountryService, CountryService>();
    

    如果启动不再报错,那就说明自动注册的逻辑确实有问题,回到第一步调整筛选规则即可。

额外注意点

  • 确保你的服务类(比如CountryService)是public的,NetCore.AutoRegisterDi默认只扫描public的非泛型类。
  • 确保服务类正确实现了对应的接口(比如CountryService : ICountryService),否则AsPublicImplementedInterfaces也无法正确注册。

内容的提问来源于stack exchange,提问作者santosh kumar patro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 13:52:37