One of my viewmodels contains reference to Service Controller.
I’ve implemented the IDisposable on this viewmodel.
Now, i am creating List of this viewmodel in some other viewModel.
Do i need to implement IDisposable on other viewmodel.
One of my viewmodels contains reference to Service Controller. I’ve implemented the IDisposable on
Share
I’d back this up a step and ask how your view model gets ahold of this reference to ServiceController. Are you injecting it as a dependency? Does the ServiceController have a longer lifespan than the ViewModel? If the ViewModel is creating it, then the Disposable makes sense, but if you are injecting this dependency or it is somehow being shared among the instances of your “ViewModelA”, then it ought not to be up to that class to dispose of the ServiceController. I mean, it doesn’t make sense for you to invoke Dispose() on some object that might be legitimately in scope elsewhere.
But, assuming this does make sense (you have some list of VMs creating their ServiceController internally), then whether or not ViewModelB needs to implement IDisposable depends on the lifetime of the ViewModelA instances. If these are persisted as class level variables then yes, probably, you should dispose of them in VMB’s IDisposable. If they are created, used and discarded in a method, then no need.
Reasoning about IDisposable is really all about considering the lifetimes of your objects. It makes sense when you have some resource that needs to be released but is kept around for the duration of an instance’s lifetime. And, when this happens, you’ll want to invoke Dispose() in the same scope as you created it in (often, as mentioned by Ashish, with the “using” keyword).