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

同一C# Asp.NetCore 3.1项目中NSwag仅本地运行失败的问题求助

NSwag throws "No service for type 'Microsoft.Extensions.DependencyInjection.IServiceProviderFactory<Autofac.ContainerBuilder>'" in ASP.NET Core 3.1 project (works for colleagues)

I totally get how frustrating this kind of environment-specific issue can be—code works for everyone else, every standard troubleshooting step you try fails, and you're stuck wondering why your local setup is the odd one out. Let's break down this problem and target the root causes that are unique to your machine.

Why This Happens

The error means NSwag can't locate the Autofac service provider factory when it spins up your project's web host to generate the Swagger document. Since you've ruled out code issues (colleagues can run it, fresh clone fails only for you), this is almost certainly a local environment discrepancy related to dependency loading, SDK versions, or cached assets.

Step-by-Step Fixes

1. Align .NET Core 3.1 SDK Versions

First, confirm you're using the exact same SDK version as your colleagues:

  • Run dotnet --list-sdks in your terminal to check installed versions
  • Ask your team for their output and install the matching 3.1.x SDK if needed
  • Add a global.json file at your solution root to lock the SDK version:
    {
      "sdk": {
        "version": "3.1.426" // Replace with your team's exact version
      }
    }
    

2. Purge Cached Dependencies

Corrupted NuGet or node modules caches are a common culprit:

  • Clear NuGet caches: dotnet nuget locals all --clear
  • Delete your project's bin and obj folders, then run dotnet restore
  • Delete the node_modules folder in your API project, then run npm install to re-download NSwag and dependencies

3. Force NSwag to Use Project-Local Autofac Assemblies

NSwag might be trying to load outdated or mismatched Autofac binaries from a global cache. Explicitly point it to your project's dependencies:

  • Update your openapi.nswag file to include explicit assembly paths:
    "assemblyPaths": [
      "../B2B.API/bin/Debug/netcoreapp3.1/Autofac.dll",
      "../B2B.API/bin/Debug/netcoreapp3.1/Autofac.Extensions.DependencyInjection.dll",
      "../B2B.API/bin/Debug/netcoreapp3.1/B2B.API.dll"
    ]
    
  • Or pass reference paths directly in the NSwag command:
    .\nswag run ..\..\openapi.nswag /runtime:NetCore31 /reference:../B2B.API/bin/Debug/netcoreapp3.1/Autofac.dll /reference:../B2B.API/bin/Debug/netcoreapp3.1/Autofac.Extensions.DependencyInjection.dll
    

4. Eliminate Global Tool Conflicts

If you have a global NSwag CLI installed, it might conflict with your project's local version:

  • Check for global tools: dotnet tool list --global
  • Uninstall the global NSwag CLI if present: dotnet tool uninstall -g NSwagCLI
  • Ensure your terminal is using the project-local NSwag binary from node_modules (the path in your error log confirms this, but double-check no global PATH entries are overriding it)

5. Temporary Program.cs Adjustment for NSwag

As a last resort, modify your Program.cs to skip Autofac registration when NSwag is running:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((context, services) =>
        {
            // Detect if we're running in NSwag's generation context
            var isNSwagGenerator = Environment.GetEnvironmentVariable("NSWAG_GENERATOR") == "true";
            if (!isNSwagGenerator)
            {
                services.AddAutofac();
            }
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Then run NSwag with the environment variable set:

set NSWAG_GENERATOR=true && .\nswag run ..\..\openapi.nswag /runtime:NetCore31

Final Notes

Environment-specific issues like this almost always boil down to subtle differences in SDK versions, cached assets, or global tooling. Focus on comparing your setup side-by-side with a colleague's—even small discrepancies (like a minor SDK patch version) can cause dependency loading failures.

内容的提问来源于stack exchange,提问作者jhe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:09:07