6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ASP.NET Coreの依存性注入で登録漏れを実行前に見つける設定

6
Posted at

はじめに

自分用メモですが、同じ状況の方の参考になれば幸いです。
WPF と ASP.NET の API 開発を長年やっています。

問題点

DI(依存性注入)でサービスの登録を忘れた場合、コントローラーで呼び出すと 実行時エラー になります。
これが発生すると、原因調査や修正がとても面倒です。

対応

起動時にサービス登録漏れを検出できるよう、
ValidateOnBuildValidateScopes を有効化します。

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseDefaultServiceProvider((_, options) =>
{
    options.ValidateScopes = true;  // スコープ検証
    options.ValidateOnBuild = true; // ビルド時検証
});

builder.Services.AddControllers()
    .AddControllersAsServices();

この設定を行うと、実行時エラーが起動時エラーに変わります。
ChatGPT から教えてもらった方法ですが、とても重宝しています。

6
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?