C#
DbContextのライフサイクル登録—連載第4回との接続
出典: ASP.NET MVC 5 で DI は業務系に要るのか — 入れない派の論点も書く — DbContextのライフサイクル登録—連載第4回との接続
// ✅ DbContextのライフサイクル別の挙動
// Singleton:複数リクエストで同じインスタンス→ ❌変更追跡が混ざる事故
container.RegisterType<MyDbContext>(new ContainerControlledLifetimeManager()); // ❌ NG
// Transient:同一リクエスト内でも別インスタンス→ ❌ Service Aの変更がService Bから見えない
container.RegisterType<MyDbContext>(new TransientLifetimeManager()); // ❌ NG
// ✅ PerRequest:リクエスト単位で1インスタンス、リクエスト終了でDispose
container.RegisterType<MyDbContext>(new PerRequestLifetimeManager()); // ✅本命
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「DbContextのライフサイクル登録—連載第4回との接続」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
4 件// ✅段階1: DIなし(Controller内でnew) public class CustomerController : Controller { private CustomerService _service;未収録
段階1: DIなし— Controller内で直接new
#63e0ca06e49e
// ❌段階2:サービスロケータ(アンチパターン扱い) public static class ServiceLocator { public static ICustomerService GetCustomerService()未収録
段階2:サービスロケータ—アンチパターン認定
#b6cf76b11634
// ✅段階3:コンストラクタインジェクション(DI本命) public class CustomerController : Controller { private readonly ICustomerService _service;未収録
段階3:コンストラクタインジェクション— DIコンテナの本命
#cd2c61a185a2
// ✅定石: Unity DIコンテナ設定(App_Start/UnityConfig.cs) using Unity; using Unity.Lifetime; using Unity.AspNet.Mvc;未収録
Unity DIコンテナの設定— ASP.NET MVC 5への組み込み
#d3c77983766f
