我试着调试我从教程中得到的代码,但我在构建中得到了这个错误。我正在使用.Net 6
An unhandled exception of type 'System.AggregateException' occurred in Microsoft.Extensions.DependencyInjection.dll: 'Some services are not able to be constructed'
Inner exceptions found, see $exception in variables window for more details.
Innermost exception System.InvalidOperationException : Unable to activate type 'fixit.Data.DataContext'. The following constructors are ambiguous:
Void .ctor(Microsoft.Extensions.Configuration.IConfiguration)
Void .ctor(Microsoft.EntityFrameworkCore.DbContextOptions`1[fixit.Data.DataContext])
这是我的程序. cs我改变了很多,因为它很难重写从startup.cs.net5没有得到一个错误
using fixit.Data;
using fixit.Models;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddDbContext<DataContext>(opt => opt.UseMySql(builder.Configuration.GetConnectionString("WebApiDatabase"),
ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("WebApiDatabase"))));
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddCors(option =>
{
option.AddPolicy("allowedOrigin",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
);
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddScoped<IRepository<Service>, ServiceRepository>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run();
i在行 var app = builder.Build()中获得错误异常; .这是我的datacontext.cs,因为它似乎是错误来自这里。
using fixit.Models;
using Microsoft.EntityFrameworkCore;
namespace fixit.Data
{
public class DataContext : DbContext
{
protected readonly IConfiguration Configuration;
public DataContext(IConfiguration configuration)
{
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// connect to mysql with connection string from app settings
var connectionString = Configuration.GetConnectionString("WebApiDatabase");
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
}
public DataContext() { }
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<Service> Service { get; set; }
}
}
如何解决这个问题?我尝试使用API控制器将Flutter与Web-API和IM集成在一起,
1条答案
按热度按时间p3rjfoxz1#
这个问题的原因是使用
DataContext
构造函数两次,然后我们得到错误消息The following constructors are ambiguous
。解决方案
像下面这样修改你的代码,问题就解决了。