在使用 EF4.1 及 Unity 時遇到了資料更新後還會取得舊資料的問題。發現原來是因為使用了 Unity 的關係。
Unity 記下了DBContext 的Instance 而不會在每次 request 的時後重新建立。所以會產生取得舊資料的問題。要記得加上 HierarchicalLifetimeManager 才能夠讓 dbContext 在每次 Request 的時後重建。
1: private static IUnityContainer BuildUnityContainer()
2: {3: var container = new UnityContainer();
4: 5: container.RegisterType<ILtsService, LtsService>(); 6: container.RegisterType<IEmpService, EmpService>(); 7: 8: container.RegisterType<WEKIDSDBEntities>(new HierarchicalLifetimeManager());
9: container.RegisterType<CodeGroupHelper>(new PerThreadLifetimeManager());
10: container.RegisterType<SeqNoHelper>(new PerThreadLifetimeManager());
11: 12: container.RegisterInstance<IUnityContainer>(container, new PerThreadLifetimeManager());
13: 14: container.RegisterControllers(); 15: 16: return container;
17: }
參考資料:
Introducing The Unity.Mvc3 NuGet Package To Reconcile MVC3, Unity and IDisposable
沒有留言:
張貼留言