Reputation: 1093
In my ASP.NET MVC app I have a controller like this:
[HttpPost]
public ActionResult CreateTestCategory(TestCategory testCategory)
{
BLL.Admin.CreateTestCategory obj = new BLL.Admin.CreateTestCategory();
obj.Create(testCategory.TestCategoryName);
//((IDisposable)obj).Dispose();
return RedirectToAction("TestCategory", "Admin");
}
Here the BLL.Admin.CreateTestCategory
is in another layer and it does not implement IDisposable. It just makes some EF database calls and those calls are disposed in their own way using Repository pattern, so no worries there. But in this controller I created an object obj
of that class. After working it out I want to destroy/dispose that obj
manually. So the line I commented out, is this the only way to dispose obj
?
The reason I did not make BLL.Admin.CreateTestCategory
to implement IDisposable is that, there might be a hundred classes like it. I dont want to go to each one and implement IDisposable then use the using
block, its painful, instead I want to just dispose it manually after creating it. I also dont want to wait for GC. So what is the perfect reliable way of doing it?
Upvotes: 0
Views: 2877
Reputation: 8655
This question has already been answered in a roundabout way in the comments on the question itself, but to sum up what CodingYoshi, Evk, and Fabjan have said there...
IDisposable
is for cleaning up resources that are not managed by the .NET runtime. If you need to clean up connections to databases, file locks, etc, then you really should be using IDisposable
. For managed memory, the garbage collector will take care of it better than you can in almost any circumstances. Destructors can be used, but are generally not necessary.
References:
MSDN on the Dispose Pattern: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/dispose-pattern
MSDN on Finalizers: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/destructors
What is the difference between using IDisposable vs a destructor in C#?
Upvotes: 2