Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject and DataContext disposal

Tags:

I'm using Ninject to retrieve my DataContext from the kernel and I was wondering if Ninject automatically disposes the DataContext, or how he handles the dispose() behaviour. From own experiences I know disposing the datacontext is pretty important and that whenever you create a direct object of the DataContext (as in: new DataContext()) you should use a using() block.

My question thus is: When im retrieving my DataContext from the kernel, should I still have to use a using() block? Or does Ninject fix this for me?

like image 309
Bas Avatar asked Jun 03 '10 09:06

Bas


1 Answers

I am investigating this for my colleague Bas. I was looking in the Ninject 2 source code (http://github.com/ninject/ninject.git), and there seems to be some life cycle management.

When there's an other scope than transient, then the garbage collection of that scope will trigger the deactivation (through the pipeline) of all instances linked to that scope. On deactivation one of the default strategies is DisposableStrategy, this strategy will dispose the instance if it's IDisposable!

I saw a lot of answers on stackoveflow that Ninject doesn't do any life cycle management, maybe this was true for a previous version of Ninject?

But this behaviour is quite tricky, since when using injected services you are not aware of the scope. Because of that you don't know if you have to dispose the object yourself (transient) or that Ninject will take care of this.

Changes to the scope of a service could therefor introduce bugs.

like image 164
JJoos Avatar answered Oct 09 '22 01:10

JJoos