実現したいこと
asp.net core MVCでDB接続をしたくて
https://localhost:44338/XXX(Controller名)/TestDbContext
でアクセスするも画像のようなエラーが出る。
このエラーが発生する主な理由は、WebAppDBContext がサービスコンテナに正しく登録されていないか、または YahooRestaurantController がサービスコンテナによってインスタンス化されていないため
らしいがchatgptに聞いてもどこがおかしくて接続できないのかわかりませんでした。
発生している問題・分からないこと
エラーメッセージ
error
1An unhandled exception occurred while processing the request. 2InvalidOperationException: Unable to resolve service for type 'WebApp.Models.WebAppDBContext' while attempting to activate 'WebApp.Controllers.YahooRestaurantController'. 3Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) 4 5Stack Query Cookies Headers Routing 6InvalidOperationException: Unable to resolve service for type 'WebApp.Models.WebAppDBContext' while attempting to activate 'WebApp.Controllers.YahooRestaurantController'. 7Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) 8lambda_method19(Closure , IServiceProvider , object[] ) 9Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext) 10Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext) 11Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) 12Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() 13Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) 14Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) 15Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) 16Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() 17Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) 18Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) 19Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 20Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 21Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
該当のソースコード
WebAppDBContext.cs
1using Microsoft.EntityFrameworkCore; 2 3namespace WebApp.Models 4{ 5 public class WebAppDBContext: DbContext 6 { 7 public WebAppDBContext(DbContextOptions<WebAppDBContext> options) : base(options) { } 8 public DbSet<YahooRestaurant> yahoo_restaurant { get; set; } 9 } 10}
Startup.cs
1using Microsoft.AspNetCore.Builder; 2using Microsoft.AspNetCore.Hosting; 3using Microsoft.Extensions.Configuration; 4using Microsoft.Extensions.DependencyInjection; 5using Microsoft.Extensions.Hosting; 6 7//DB情報追加 8using Microsoft.EntityFrameworkCore; 9using WebApp.Models; 10 11namespace WebApp 12{ 13 public class Startup 14 { 15 public void Configure(IApplicationBuilder app) 16 { 17 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 18 } 19 20 //ここからconfigurationを設定 21 public Startup(IConfiguration configuration) 22 { 23 Configuration = configuration; 24 } 25 public IConfiguration Configuration { get; } 26 //ここまでconfigurationを設定 27 28 public void ConfigureServices(IServiceCollection services) 29 { 30 services.AddControllersWithViews(); 31 // 他のサービスの設定 32 // データベース接続文字列を取得し、DbContext をサービスコンテナに登録 33 services.AddDbContext<WebAppDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("WebAppDBConnectionString"))); 34 35 } 36 37 } 38} 39
appsettings.json
1{ 2 "Logging": { 3 "LogLevel": { 4 "Default": "Information", 5 "Microsoft.AspNetCore": "Warning" 6 } 7 }, 8 "AllowedHosts": "*", 9 "ConnectionStrings": { 10 "WebAppDBConnectionString": "Server=localhost\\SQLEXPRESS01;Database=WebApp;Trusted_Connection=True;" 11 } 12 13} 14
XXXController.cs
1using Azure; 2using Microsoft.AspNetCore.Mvc; 3using Newtonsoft.Json; 4using System.Diagnostics; 5using System; 6//追加 7using System.Linq; 8using System.Net; 9using WebApp.Models; 10using static Microsoft.EntityFrameworkCore.DbLoggerCategory; 11 12namespace WebApp.Controllers 13{ 14 public class YahooRestaurantController : Controller 15 { 16 17 private readonly WebAppDBContext _context; 18 19 public XXXController(WebAppDBContext context) 20 { 21 _context = context; 22 } 23 24 public IActionResult TestDbContext() 25 { 26 var test = _context.yahoo_restaurant.FirstOrDefault(); 27 if (test == null) 28 { 29 // データがない場合の処理 30 return NotFound("No restaurants found."); 31 } 32 return Ok(test); 33 } 34 } 35} 36
Program.cs
1//Webアプリケーションのビルダーを作成 2var builder = WebApplication.CreateBuilder(args); 3 4// Add services to the container. 5builder.Services.AddControllersWithViews(); 6 7//Webアプリケーションを構築 8var app = builder.Build(); 9 10// Configure the HTTP request pipeline. 11if (!app.Environment.IsDevelopment()) 12{ 13 app.UseExceptionHandler("/Home/Error"); 14 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 15 app.UseHsts(); 16} 17 18app.UseHttpsRedirection(); 19app.UseStaticFiles(); 20 21app.UseRouting(); 22 23app.UseAuthorization(); 24 25app.MapControllerRoute( 26 name: "default", 27 pattern: "{controller=Home}/{action=Index}/{id?}"); 28 29app.Run(); 30
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
chatgptなどのやり方を参考にしているがエラーが解消されませんでした
補足
.NET6
Startup.csは手動で作成しました。

回答1件
あなたの回答
tips
プレビュー