dependency injection - C# Implementing IDisposable and Disposing of Objects -



dependency injection - C# Implementing IDisposable and Disposing of Objects -

lets have following:

public void somemethod() { myfirstclass c = new myfirstclass(); using(var sec = new mysecondclass(c)) { using(var 3rd = new mythirdclass(c)) { //do stuff sec , 3rd } } } public myfirstclass() { //do construtor stuff } public class mysecondclass { public mysecondclass(myfirstclass cls) { privatefirstclassvar = cls; } public void dispose() { dispose(true); gc.suppressfinalize(this); } public virtual void dispose(bool disposing) { if(_disposed) return; if(disposing) { privatefirstclassvar = null; } _disposed = true; } } public mythirdclass(myfirstclass cls) { privatefirstclassvar = cls; //same dispose method mysecondclass }

if 3 implement idisposable , set variables in mysecondclass , mythirdclass null, set original object (which same object in both cases) null or local variables reference it? have never tried using dependency injection before , want create sure don't screw myself.

edited: question (after editing) disposing of sec , 3rd c?

the reply looks "no" me, if understand you. why original reference set null because 2 other references set null? however, when "somemethod" exits, "c" go out of scope , should eligible garbage collection.

let's walk through it:

public void somemethod() { // first (local-scope) reference "c": myfirstclass c = new myfirstclass(); // 2 more references in "second" , "third": mysecondclass sec = new mysecondclass(c); mythirdclass 3rd = new mythirdclass(c); //do stuff // 2nd , 3rd references set null sec = 3rd = null; // when "somemethod" exits, "c" out of scope -- no references object remain }

one other note -- create sure phone call dispose on idisposable objects -- garbage collector won't you. 1 easy way using:

public void somemethod() { using (myfirstclass c = new myfirstclass()) { using (mysecondclass sec = new mysecondclass(c)) { using (mythirdclass 3rd = new mythirdclass(c)) { //do stuff } } } }

c# dependency-injection

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -