Controllers and IDisposable - c#

If I make a controller implement IDisposable, I assume that the Dispose method still won't be invoked by the GC. So that means I would have to add:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
if (!isDalDisposed)
{
isDalDisposed = true;
if (disposing)
DAL.Dispose();
}
base.Dispose(disposing);
}
I have read that using Object.Finalize is bad practice and should be avoided where possible.
The issue I have is that my "services" are created in the default constructor which does not permit me to use a using statement to control the lifetime of each service. So, what would be the correct way to handle this issue?

Web API's ApiController has already implemented IDisposable and provides convenient virtual method for developers to override, which is the Dispose(bool) method you are using. So all you need to do is remove your own boolean flag and just check only disposing parameter.
protected override void Dispose(bool disposing)
{
if (disposing)
{
DAL.Dispose();
}
base.Dispose(disposing);
}

If you can override protected void Dispose(bool disposing), it would imply that the base class uses the Disposable pattern, and already implements IDisposable.
Just remove the IDisposable interface and the public void Dispose() method, and it should work.

Is there any specific reason why you create the service in the constructor?
Since the controller is instantiated per request you can create the service in the action itself within a 'using' block. The lifetime of the service is anways limited to the action.

Related

Properly dispose derived class

I am trying to implement the IDisposable pattern on a derived class, and it's not working as expecting to work,
Suppose I have two classes and I want to call the Dispose method of the derived class:
Below is the code of my base class
public class BaseClass : IDisposable
{
// To detect redundant calls
private bool _disposedValue;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
_disposedValue = true;
}
}
}
And I've something like this as a derived class
public class DerivedClass : BaseClass
{
// To detect redundant calls
private bool _disposedValue;
// Protected implementation of Dispose pattern.
protected override void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}
_disposedValue = true;
}
// Call base class implementation.
base.Dispose(disposing);
}
}
And I've some wrapper class
public class WrapperClass : IDisposable
{
public ReadOnlyCollection<BaseClass> Items { get; set;}
// To detect redundant calls
private bool _disposedValue;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
foreach (var item in Items)
{
item.Dispose();
}
}
_disposedValue = true;
}
}
}
My issue is in the wrapper class, it doesn't call the Dispose method of the DerivedClass, and it calls the Dispose method of the BaseClass instead.
Update
It's my bad, I forget to say that the collections of items were created by NSubstitute like below:
// Having this will not call the Dispose method of the derived class
Items = new ReadOnlyCollection<BaseClass>(new List<BaseClass>
{
Substitute.For<DerivedClass>()
})
// Having this will call the Dispose method of the derived class
Items = new ReadOnlyCollection<BaseClass>(new List<BaseClass>
{
new DerivedClass>()
})
The public implementation of the Dispose() pattern in the documentation is there as an example to handle every case and contingency. It's always "safe" to do the whole thing, but it's also true that most of the time you can skip most of the pattern.
Especially regarding finalizers: you should only need a finalizer if you are creating an original wrapper implementation for a brand new kind of unmanaged resource. Each unmanaged resource type only needs one finalizer, at the root of the IDisposable inheritance tree. And if you don't add a finalizer, you don't need to worry about GC.SuppressFinalize(). Remove that, and some other balls drop as well.
In short, we can reduce the pattern for your DerivedClass all the way down to this:
public class DerivedClass : BaseClass
{
}
This DerivedClass type still provides the Dispose() method and IDisposable implementation inherited from it's parent, and if it doesn't introduce any other unmanaged resources that's all it needs.
My issue is in the wrapper class, it doesn't call the Dispose method of the DerivedClass, and it calls the Dispose method of the BaseClass instead.
When the base.Dispose() calls Dispose(true) the method override in the derived class is executed, which in turn will call base. Dispose(true).
DerivedClass doesn't appear to override Dispose(). Consequently, the base class version is invoked.
Add a public void Dispose() method that calls your protected void Dispose(bool disposing) implementation in DerivedClass.

Should IDisposable::Dispose() be virtual

Say a factory for SomeDisposable actually is creating/returning a sort of watch dog Wrapper
public class Wrapper : SomeDisposable
{
public new /*:(*/ Dispose() { ... };
}
and the caller uses like
using (SomeDisposable sd = SomeDisposableFactory.Create(...))
{
} // Wrapper.Dispose() never called.
The Wrapper.Dispose() is never called. If Dispose() were virtual then Wrapper.Dispose() would be called.
The IDisposable interface does not guarantee that the other best practice method virtual Dispose(bool) actually exists or enforce that either be virtual so it cannot be generally relied on to exist (it is only a recommended pattern). Interfaces currently do not allow constraints on virtual.
What are some pros and cons for not making the recommended Dispose() pattern virtual which would have solved this particular dilemma. Should C# allow a way of forcing virtual methods via an interface (since abstract classes aren't popular as contract definitions).
No. The pattern actually says that Dispose() (non-virtual) should call a protected virtual void Dispose(bool) method. This guarantees that the base class Dispose call can pass up the hierarchy properly.
This is spelled out in the documentation for IDisposable:
It should provide one public, non-virtual Dispose() method and a protected virtual Dispose(Boolean disposing) method.
The Dispose() method must call Dispose(true) and should suppress finalization for performance.
The base type should not include any finalizers.
This is already solved.
Disposable types which are not sealed should use the common dispose pattern:
public class DisposableResourceHolder : IDisposable
{
private SafeHandle resource; // handle to a resource
public DisposableResourceHolder()
{
this.resource = ... // allocates the resource
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose managed resources.
if (resource != null) resource.Dispose();
}
// free unmanaged resources.
}
}

Where to call base method?

EDIT: To eager editors, please read the FULL question In addition, since this question is not only about disposing.
So far I've seen this:
protected override Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
c.Dispose()
}
and this:
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Dispose managed resources.
}
// There are no unmanaged resources to release, but
// if we add them, they need to be released here.
}
disposed = true;
// If it is available, make the call to the
// base class's Dispose(Boolean) method
base.Dispose(disposing);
}
And Microsoft says CA2215: Dispose methods should call base class dispose, here. In addition, since this question is not only about disposing, here is another example from Microsoft calling base at the last line.
Which one is the correct/most common/better if any?
Your second snippet is doubtful, depending on whether disposed is a protected field from the base class or not.
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Dispose managed resources.
}
}
disposed = true;
base.Dispose(disposing); // wrong if base.Disposing() depends on disposed
}
The issues to consider are exceptions and dependencies between base and derived class. So use a try/finally and put the base call last. The most general pattern would look like:
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Dispose managed resources.
}
}
base.Dispose(disposing);
disposed = true; // inherited or local field
}
It's all about sequence of calls or control-flow, if you wish.
In first example dispose of base class base.Dispose() is called for first and after executed the code of the class itself. In second case, instead, vice versa.
So both of them are correct from behavior point of view, and you have to pick that one which fits best your current requirement, it can vary in the same program in regard of type naturally.

How do you "properly" implement Dispose() (according to FxCop) when your implementation is an empty method? (CA1063)

I have an implementation of an interface, and that interface extends IDisposable. In my particular implementation of the interface, I don't need to dispose anything, so I just have an empty Dispose() method.
public interface IMyStuff : IDisposable
{
}
public MyStuffImpl : IMyStuff
{
public void Dispose()
{
}
}
Now in FxCop, this results in a CA1063:
Error, Certainty 95, for ImplementIDisposableCorrectly
{
Resolution : "Provide an overridable implementation of Dispose(
bool) on 'MyStuffImpl' or mark the type as sealed.
A call to Dispose(false) should only clean up native
resources. A call to Dispose(true) should clean up
both managed and native resources."
}
CriticalWarning, Certainty 75, for CallGCSuppressFinalizeCorrectly
{
Resolution : "Change 'MyStuffImpl.Dispose()' to call 'GC.SuppressFinalize(
object)'. This will prevent derived types that introduce
a finalizer from needing to re-implement 'IDisposable'
to call it."
}
Error, Certainty 95, for ImplementIDisposableCorrectly
{
Resolution : "Modify 'MyStuffImpl.Dispose()' so that it
calls Dispose(true), then calls GC.SuppressFinalize
on the current object instance ('this' or 'Me' in Visual
Basic), and then returns."
}
So, it looks like I can resolve this in one of 2 ways:
Make the class sealed:
public sealed MyStuffImpl : IMyStuff
{
public void Dispose()
{
}
}
Implement part of the typical pattern:
public MyStuffImpl : IMyStuff
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
}
}
In my case, I don't plan on this implementation ever being extended, so I will probably resolve it by making it sealed, but I admit I don't really understand why it matters if it is sealed or not.
Also, just because my class is sealed, FxCop no longer tells me that Dispose() should call GC.SupressFinalize(this); but is that really true? Is it "better" in .NET to just always call SupressFinalize in Dispose regardless?
SuppressFinalize() is meaningless unless your instance has a finalizer.
If your class doesn't have a finalizer, but is not sealed, you should still SuppressFinalize, in case an inherited class adds a finalizer.
Both of your options are correct, except that Dispose(bool) needs to be protected virtual.
In your "implement part of the typical pattern" option, you should make your Dispose(bool) method protected virtual:
protected virtual void Dispose(bool disposing)
{
}
That will provide subclasses an opportunity to handle disposal of any resources they manage. That's the meaning of "overridable" in "Provide an overridable implementation of Dispose(bool)"
Of course, public virtual would also satisfy FxCop.

How to better implement .NET IDisposable classes?

Forgive me in advance if this question is a little too open-ended, but I've seen similar language discussion posts here so I figured I'd take the plunge.
Anyway, I have read several MSDN help pages and various other blogs on the subject of properly implementing IDisposable classes. I feel like I understand things pretty well, but I have to wonder if there's a flaw in the suggested class structure:
public class DisposableBase : IDisposable
{
private bool mDisposed;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!mDisposed)
{
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
}
Anytime the above is supposed to serve as a base class, you rely on the implementer of the subclass to properly override the Dispose(bool) method where necessary. In short, derived classes must ensure they invoke the base Dispose(bool) method from within their overridden version. If not, the base class' unmanaged resources may never get freed, defeating the primary purpose of the IDisposable interface.
We all know the benefits of virtual methods, but it seems like in this case their design falls short. In fact, I think this particular shortcoming of virtual methods manifests itself frequently when trying to design visual components and similar base/derived class structures.
Consider the following change, using a protected event rather than a protected virtual method:
public class DisposeEventArgs : EventArgs
{
public bool Disposing { get; protected set; }
public DisposeEventArgs(bool disposing)
{
Disposing = disposing;
}
}
public class DisposableBase : IDisposable
{
private bool mDisposed;
protected event EventHandler<DisposeEventArgs> Disposing;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// This method is now private rather than protected virtual
private void Dispose(bool disposing)
{
if (!mDisposed)
{
// Allow subclasses to react to disposing event
AtDisposing(new DisposeEventArgs(disposing));
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
private void AtDisposing(DisposeEventArgs args)
{
try
{
EventHandler<DisposeEventArgs> handler = Disposing;
if (handler != null) handler(this, args);
}
catch
{
}
}
}
With this design, the base class' Dispose(bool) method will always be called, regardless of whether subclasses subscribe to the Disposing event or not. The biggest flaw that I can see with this revised setup is that there is no predetermined order for when event listeners are called. This could be problematic if there are multiple levels of inheritance, e.g. SubclassA's listener might be triggered before its child SubclassB's listener. Is this flaw serious enough to invalidate my revised design?
This design dilemma makes me wish there were some sort of modifier for methods that was similar to virtual but which would ensure that the base class' method was always called, even if a subclass overrode that function. If there's a better way to achieve this, I would greatly appreciate your suggestions.
You're using an event here when really you want to use an inheritance mechanism like virtual. For scenarios like this where I want to ensure my implementation is always called but want to allow for base class customization I use the following pattern
private void Dispose(bool disposing)
if (mDisposed) {
return;
}
if (disposing) {
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
DisposeCore(disposing);
}
protected virtual void DisposeCore(bool disposing) {
// Do nothing by default
}
With this pattern I've ensured my base class Dispose implementation will always be called. Derived classes can't stop me by simply forgetting to call a base method. They can still opt into the dispose pattern by overriding DisposeCore but they can't break the base class contract.
The derived class can simply re-implement IDisposable and thus prevent your dispose method from being called, so you can't ensure that either.
Personally I wouldn't use either pattern. I prefer building on SafeHandle and similar mechanisms, instead of implementing finalizers myself.
Consider making it apparent that Dispose is not being called so someone will catch it. Of course Debug.WriteLine will only be called when the code is compiled with DEBUG compiler directive defined.
public class DisposableBase : IDisposable
{
private bool mDisposed;
~DisposableBase()
{
if (!mDisposed)
System.Diagnostics.Debug.WriteLine ("Object not disposed: " + this + "(" + GetHashCode() + ")";
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
You can break it down:
A destructor (finalizer) is only needed for unmanaged resources.
Using a Safehandle can turn an unmanged resource into a managed resource.
Ergo: You won't need a destructor. That halves the Dispose pattern.
The reference design uses a virtual void Dispose(bool) to cater for the Base/Derived class problem. This puts the burden on the derived class to call base.Dispose(disposing), the core of your question. I use 2 approaches:
1) Prevent it. With a sealed base-class you won't have to worry.
sealed class Foo:IDisposable
{
void Dispose() { _member.Dispose(); }
}
2) Check it. Like #j-agent's answer but conditional. When performance could be an issue then you don't want the finalizers in Production code:
class Foo:IDisposable
{
void Dispose() { Dispose(true); }
[Conditional("TEST")] // or "DEBUG"
~Foo { throw new InvalidOperation("somebody forgot to Dispose") }
}
The destructor is going to be called no matter if any subclass overrides Dispose() (can be via override or new) but your destructor is going to be called ( ~DisposableBase() ) so i bet putting your logic for cleanup there can be a good starting point.
Here is an intersting article about destructors: http://www.c-sharpcorner.com/UploadFile/chandrahundigam/UnderstandingDestructors11192005021208AM/UnderstandingDestructors.aspx

Categories

Resources