Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach for dependency injection of data connections in singletons

I have some "caching" objects in my application, that get a IRepository (custom repository pattern contract) by dependency injection (Ninject). Those objects only uses the repository once, but they have a Refresh function that forces the owner to refresh itself. They are singletons, are created only once, and a ManualResetEvent ensures that all requests are blocked till it is loaded.

The IRepositories are EF CodeFirst based, so is it OK just to simply ensure the connection is closed and keep the reference to the DbContext there forever?

I have disabled the proxies and the lazy loading, so... is OK to have long references from the root of the caching object to hundreds of these cached POCO entities?

Cheers.

like image 399
vtortola Avatar asked Nov 04 '22 06:11

vtortola


1 Answers

We reference to comments from Julie Lerman, http://msdn.microsoft.com/en-us/magazine/ee532098.aspx?sdmr=JulieLerman the recommendation is to have several/many smaller contexts and in the case of web scenarios create a new context each call. Although she writes about Second-Level Caching in the Entity Framework and AppFabric.

Over time, the context would be contain many objects and the performance would decline accordingly. I think this site has some good tips on EF performance. eg generated views. http://msdn.microsoft.com/en-us/data/hh949853

my personal recommendation, that I cant claim is best practice, but from someone who is concerned about performance, is that small bounded context each call is a solid long term compromise. Use generated views to keep the initial load time as small as possible.

you could potentially manage a permanent DBContext in such a way as to drop unused objects from the context. Or use a caching library with events to do so. Not a small task.

I would be interested in the solution you finally select. please post.

like image 84
phil soady Avatar answered Nov 08 '22 11:11

phil soady