【问题标题】:Unable to resolve service context while attempting to activate controller when scaffolding脚手架时尝试激活控制器时无法解析服务上下文
【发布时间】:2021-07-19 17:50:09
【问题描述】:

我正在做一个简单的HTTP GET 操作,点击我的网址后,我会将人员数据显示为JSON

起初,一切正常

工作代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Apitest4.Models;

namespace Apitest4.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PeopleController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<Person> Get()
        {
            using (var context = new ModelContext())
            {
                return context.People.ToList();
            }
        }
    }
}

您看到的上述代码是WeatherController (Visual Studio 2019) 的略微修改版本,我用它来制作我自己的PeopleController。这段代码给了我预期的正确的 API 响应

然后我想使用自动化方法来做同样的事情,因为我必须覆盖很多表

[对比代码:2019]

[控制器(右键单击)>添加>New Sacffolded Item>Api Controller with Actions using Entity Framework]

自动生成的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Apitest4.Models;

namespace Apitest4.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PeopleController : ControllerBase
    {

        private readonly ModelContext _context;

        public PeopleController(ModelContext context)
        {
            _context = context;
        }

        // GET: api/People
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Person>>> GetPeople()
        {
            return await _context.People.ToListAsync();
        }
    }
}

这段代码给了我这个错误:

InvalidOperationException: Unable to resolve service for type 'Apitest4.Models.ModelContext' while attempting to activate 'Apitest4.Controllers.PeopleController'.

完整的错误信息:

image

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

虽然我是 .net 的新手,但我就是不明白,为什么它没有正确获取上下文?我没有更改任何导入。请指出我的错误。

TIA

【问题讨论】:

  • 嗨@Frost,这个错误信息意味着你没有注册服务。请分享您的 Startup.cs。
  • @Rena 添加了 startup.cs

标签: asp.net asp.net-mvc entity-framework asp.net-core asp.net-web-api


【解决方案1】:

请务必在 Startup.cs 中注册您的 DbContext,如下所示:

services.AddDbContext<ModelContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

参考:

https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/#dbcontext-in-dependency-injection-for-aspnet-core

更新:

将连接字符串存储在 appsettings.json 中:

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
}

【讨论】:

  • 好的。你实际上就像我的回答所说的那样。您没有在启动时注册该服务。只需将上面的代码添加到您的 startup.cs 中即可。确保数据库的连接字符串正确。更多细节你可以参考我上面分享的文档。
  • 非常感谢,它醒了,但你能告诉我如何将我的连接字符串放入配置中[现在它是硬编码的]
猜你喜欢
  • 2022-01-26
  • 2020-10-15
  • 1970-01-01
  • 2020-08-21
  • 2022-09-24
  • 1970-01-01
  • 2023-01-13
  • 2018-04-06
  • 2021-08-25
相关资源
最近更新 更多