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

ASP.NET Web API搭建REST API时遇Error CS0121方法调用歧义问题求助

ASP.NET Web API搭建REST API时遇Error CS0121方法调用歧义问题求助

问题描述

我跟着YouTube教程搭建REST API时遇到了如下错误:

Error CS0121 The call is ambiguous between the following methods or properties:
'Application.Dependency.AddApplication(Microsoft.Extensions.DependencyInjection.IServiceCollection)'
and
'Application.Dependency.AddApplication(Microsoft.Extensions.DependencyInjection.IServiceCollection)'

我知道这是因为有两个完全相同的方法导致编译器不知道选哪个,但我搞不懂为什么会出现这种情况,也不知道怎么修复。

以下是我的相关代码:

Application.Dependency.cs

using Application.Services.Authentication;
using Microsoft.Extensions.DependencyInjection;

namespace Application;

public static class Dependency {
    public static IServiceCollection AddApplication(this IServiceCollection services)
    {
        services.AddScoped<IAuthenticationService, AuthenticationService>();
        return services;
    }
}

Program.cs

using Infrastructure;
using Application;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
{
    builder.Services.AddApplication().AddInfrastructure();
    builder.Services.AddControllers();
}

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

解决方案

兄弟,我太懂你这会儿的困惑了——明明自己只在Application.Dependency里写了一次AddApplication扩展方法,结果编译器硬说有两个完全一样的版本,不知道该调用哪个对吧?别慌,咱们一步步排查解决:

  • 检查是否重复引用了Application项目/包
    你有没有不小心把Application项目引用了两次?比如既通过「项目引用」加了一遍,又误加了同名的NuGet包?
    👉 解决:右键解决方案→「管理解决方案的NuGet程序包」,看看有没有重复的Application相关包;或者右键你的WebAPI项目→「添加」→「项目引用」,确认Application项目只被勾选了一次。

  • 排查项目内的重复方法定义
    虽然你贴的Dependency.cs里只有一个AddApplication,但说不定Application项目里还有其他文件也定义了同名的Dependency静态类,并且里面也写了AddApplication方法?
    👉 解决:在Application项目里全局搜索AddApplication,看看是不是有重复的定义,找到后删掉多余的那个就行。

  • 清理旧的编译产物
    有时候之前的编译残留会搞事情——比如你之前可能写过重复的方法,后来删掉了,但WebAPI项目的bin/obj目录里还留着旧的dll,导致编译器加载了两个版本的程序集。
    👉 解决:右键解决方案→「清理解决方案」,接着再点「生成解决方案」;或者手动删掉WebAPI项目下的bin和obj文件夹,重新编译试试。

  • 确认间接依赖的一致性
    你的WebAPI项目同时引用了Application和Infrastructure,有没有可能Infrastructure项目引用的Application和WebAPI直接引用的不是同一个版本?比如Infrastructure用了NuGet包版的Application,而WebAPI用了项目引用版的?
    👉 解决:检查Infrastructure项目的依赖,确保它引用的Application和WebAPI引用的是同一个来源(要么都是项目引用,要么都是同一个版本的NuGet包)。

结合你贴的代码来看,你自己写的方法逻辑是没问题的,大概率是上面某一种环境依赖的问题,按顺序排查应该就能解决啦!

备注:内容来源于stack exchange,提问作者SilverMoon17

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 12:59:30