C
C#4d ago
Vortac

IDisposable Constructor Injection

If I new up a class to inject via constructor injection which has an IDisposable object, does the class receiving the IDisposable parameter need to implement IDisposable? eg:
using var soundEngine = new MiniAudioEngine(44100, Capability.Playback);
var player = new SoundEngine(soundEngine);
using var soundEngine = new MiniAudioEngine(44100, Capability.Playback);
var player = new SoundEngine(soundEngine);
Does player need to be using var player?
2 Replies
mtreit
mtreit4d ago
If the class stores the injected thing in a field and effectively takes ownership of that disposable, then yes it should implement IDisposable itself. And you would probably remove the other using (the first line of your code example) because you don't want two pieces of code disposing the same thing possibly at different times.
Vortac
VortacOP4d ago
Thank you!

Did you find this page helpful?