Concrete Class to Interface Disposing Question

beantownace

Active member
Joined
Feb 15, 2019
Messages
25
Programming Experience
5-10
Needing a little help with something I am blanking on with this. I am refactoring someones code and they have a concrete class some methods that I added into a new interface to design it better and unit test the methods needed. The concrete class has the IDisposable interface so for example:
public class CustomerHelper : IDisposable

I changed this to:
public class CustomerHelper : ICustomerHelper, IDisposable

The issue I am trying to figure out what to do with is through the code in many places there are using blocks for example.

using (var helper = new CustomerHelper) { //code in here }
Project uses Unity so now I have the following:
var helper = Services.Registry.CustomerHelper;
public static class ServicesRegistry
{
public static ICustomerHelper CustomerHelper => UnityContainerProvider.ResolveRequired<ICustomerHelper>();
}
What do I need to do to make sure the dispose is correct that is where I am struggling. Thanks for any info all.
 
Last edited:
That said, should you be disposing the object? I don't know how Unity works but it looks like Services.Registry.CustomerHelper is a property so, unless that property will produce a new object if and when the old one is disposed then you wouldn't dispose it. You dispose an object when you finished using it so, if you're going to use it again, you wouldn't dispose it.
 
That said, should you be disposing the object? I don't know how Unity works but it looks like Services.Registry.CustomerHelper is a property so, unless that property will produce a new object if and when the old one is disposed then you wouldn't dispose it. You dispose an object when you finished using it so, if you're going to use it again, you wouldn't dispose it.
Thank you. I should have shown the ServiceRegistry does the following:
public static class ServicesRegistry
{
public static ICustomerHelper CustomerHelper => UnityContainerProvider.ResolveRequired<ICustomerHelper>();
}
 
OK, so the type of helper is ICustomerHelper, which doesn't have a Dispose method. I guess you could then perform a conditional cast and dispose if successful, e.g.
C#:
internal void DisposeIfSupported(object obj)
{
    (obj as IDisposable)?.Dispose();
}
You can call that method and pass any object in and it will be disposed if it implements IDisposable.
 
Back
Top Bottom