Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Initialize Disposable in inherited constructor

Hey so I have a base class coming from a 3rd party dll, which is dependent on a disposable. Context: IDisposable

public class BaseValidator
{
    public BaseValidator(Context context) {}
}

We’re trying to move away from tying our classes to these dependencies. So we started relying on providers instead

public interface IContextProvider 
{
    Context Create();
}

I have a new validator that I’m writing which inherits from the BaseValidator, but I would like it to be dependent on the IContextProvider instead. So I’d like to create the context in the inherited constructor, but I would like to dispose of it in the destructor to prevent memory leaks, However I’m not sure if this is possible.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class EntityValidator: BaseValidator 
{
    public EntityValidator(IContextProvider provider) : base(provider.Create()) 
    {
    }

    ~EntityValidator()
    {
        //I'm not how I can dispose the entity I've passed into it.
    }
}

My question is, is there a trick I can use to Capture the variable passed into the base?

Note: I know I can make a work around with an external helper class, but I’m interested if anyone knows how to do this in a more savvy way.

>Solution :

If the BaseValidator class does not expose Context in a public manner, your current design would require you use reflection and knowledge of the internal implementation of BaseValidator to dispose of it, which is of course fragile.

I would instead capture the context using an intermediate constructor:

Context _context;
private EntityValidator(Context context) : base(context) 
{ 
    _context = context;
}
public EntityValidator(IContextProvider provider) : this(provider.Create())
{
    
}

Note, disposing via a finalizer (a.k.a. destructor) is not ideal due to constraints it places on the garbage collector. I’d instead have EntityValidator implement IDisposable

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading