尝试激活我的控制器时无法解析类型服务

问题描述 投票:0回答:1

从 MERN Stack 背景来看,我发现 Dotnet 很困难,我创建了控制器并注册了我的 DBContext,因为我试图将我的数据保存在 mysql 数据库中,但我仍然面临这个问题,你能发现我哪里做错了吗?

Program.cs(我的主文件):

public Program(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyDbContext>(options =>
        options.UseMySql(
            Configuration.GetConnectionString("MySqlConnection"),
            new MySqlServerVersion(new Version(8, 0, 0))));

    services.AddControllers();
}

控制器/MyDbContext.cs

using Microsoft.EntityFrameworkCore;
using Raiders.Api.Models;

namespace Raiders.Api.Data
{
    public class MyDbContext : DbContext
    {
        public DbSet<User> Users { get; set; }

        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }
    }
}

控制器/SignupController.cs

{
    [ApiController]
    [Route("[controller]")]
    public class SignupController : ControllerBase
    {
        private readonly MyDbContext _context;

        public SignupController(MyDbContext context)
        {
            _context = context;
        }

        [HttpPost]
        public IActionResult SignupUser(string username)
        {

            var newUser = new User
            {
                Username = username
            };

            _context.Users.Add(newUser);
            _context.SaveChanges();

            return Ok("User created successfully");
        }
    }
}

控制器/用户.cs

{
    public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
    }
}
c# asp.net-core .net-core
1个回答
0
投票

你的program.cs对我来说很奇怪。我认为将配置注入“程序”类是问题所在。
对于一个典型的 webapi 项目。如果您使用的 SDK >=“.net6”,您应该注册服务并访问配置,如下所示:
程序.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MyDbContext>(options =>
        options.UseMySql(
            builder.Configuration.GetConnectionString("MySqlConnection"),
            new MySqlServerVersion(new Version(8, 0, 0))));
builder.Services.AddControllers();
...
var app = builder.Build();
...
app.Run();

如果您使用.net5或更低版本,那么您应该注入“Startup.cs”,如下所示:
启动.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
...

参考:https://andrewlock.net/exploring-dotnet-6-part-2-comparing-webapplicationbuilder-to-the-generic-host/

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.