.net - When trying to use dependency injection and the IDisposable interface correctly should I inject an instance of SafeHandle? C# -
according msdn best way implement idisposable interface involves using instance of safehandle class.
in given example have following line;
safehandle handle = new safefilehandle(intptr.zero, true);
i have been reading dependency injection , tdd , understanding in order both follow tdd , implement idisposable interface correctly have this;
public class somedisposableclass : idisposable { private readonly stream _stream; private readonly idisposable _safehandle; public somedisposableclass(stream stream, idisposable safehandle) { _stream = stream; _safehandle = safehandle; } private bool disposed = false; public void dispose() { dispose(true); gc.suppressfinalize(this); } protected virtual void dispose(bool disposing) { if (disposed) return; if (disposing) { _safehandle.dispose(); _stream.dispose(); } disposed = true; } }
i injecting safehandle instead of instantiating within somedisposableclass. allow me pass in mock , assert dispose method called in event somedisposableclass instance has dispose() method called.
is correct thing when using tdd , dependency injection or taking things far? (i.e. ok instantiate classes rather injecting them or should avoid "new" plague?)
i aware there problems example (for example not obliged pass in safehandle instance, idisposable instance).
you shouldn't use di provide safehandle
class. safehandle
internal implementation detail in class, uses implement idisposable
. users of class shouldn't have know internal implementation. di intended provide class external entities class collaborates with. don't afraid use new
objects used within class.
a resource book: http://www.growing-object-oriented-software.com/ can't describe whole book here here's couple of ideas. talk "values" , "objects".
values immutable instances model fixed quantities. objects ... use mutable state model behavior on time.
the style described in book uses di connect web of "objects" collaborate each other , uses mock objects test these collaborations. on other hand, "values" created new
when needed in both production , test code , passed parameters , return values.
Comments
Post a Comment