Home > OS >  C# Initialize Disposable in inherited constructor
C# Initialize Disposable in inherited constructor

Time:09-07

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.

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.

CodePudding user response:

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

  • Related