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

.NET 6中DataContext构造函数歧义引发System.AggregateException的解决

解决System.AggregateException:DataContext构造函数歧义问题

问题根源

你的DataContext类存在多个公共构造函数:

  • 带IConfiguration的构造函数
  • 无参构造函数
  • 带DbContextOptions<DataContext>的构造函数

.NET依赖注入容器无法确定应该使用哪个构造函数实例化DataContext,因此抛出歧义错误。同时你在Program.cs中已经通过AddDbContext配置了数据库连接,DataContext中的OnConfiguring方法属于重复配置,会引发冲突。

解决方案

1. 清理DataContext类

保留仅带DbContextOptions<DataContext>的构造函数,移除其他构造函数和OnConfiguring方法,修改后的代码如下:

using fixit.Models;
using Microsoft.EntityFrameworkCore;

namespace fixit.Data
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) { }

        public DbSet<Service> Service { get; set; }
    }
}

2. 验证Program.cs的配置

你现有Program.cs中的AddDbContext配置已经正确,无需修改:

builder.Services.AddDbContext<DataContext>(opt => 
    opt.UseMySql(
        builder.Configuration.GetConnectionString("WebApiDatabase"), 
        ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("WebApiDatabase"))
    )
);

3. 可选CORS配置优化

你的代码中配置了两次CORS策略,可统一为一种更清晰的写法:

// 注册CORS命名策略
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// 管道中使用该命名策略
app.UseCors("AllowAll");

说明

  • 使用AddDbContext注册DbContext时,DI容器会自动注入DbContextOptions<DataContext>,因此仅需保留对应构造函数。
  • 移除多余构造函数消除了DI容器的歧义选择问题。
  • 移除OnConfiguring方法避免了配置冲突,确保连接配置集中在Program.cs中,符合.NET 6的极简配置风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:44:56