I'm working with a 3rd party object that implements IDisposable. In order to make it unit test "able" I build a wrapper. I understand that object implements IDisposable my wrapper needs to implement IDisposable as well.

public interface IWrapper : IDisposable
{
    void Complete();
}

public class Wrapper : IWrapper
{
    private readonly ThirdPartyLib lib;

    public Wrapper()
    {
        lib = new ThirdPartyLib();
    }

    public void Complete()
    {
        lib.Comlete();
    }

    public void Dispose()
    {
        lib.Dispose();
    }
}

public class Processor : IProcessor
{
    private readonly IWrapper wrapper;
    public Processor(IWrapper wrapper)
    {
        this.wrapper = wrapper;
    }

    public void Process()
    {
        // do some work
        using (wrapper) {
            // do more work
        }
    }
}

Suppose Processor is injected in some class that is using it and Process() is executed

  • What happends to wrapper if we call Process() again? - wouldn't ThirdPartyLib() throw an exception since it was created only once (in wrappers constructor) and now it has been disposed
  • Does it not get disposed as long as there is a reference to it?
  • Should the wrapper maybe be build in such a way that new() "ing" of ThirdPartyLib be performed not in a constructor but in a seperate method, say Begin() - like so:
public class Wrapper : IWrapper
    {
      private ThirdPartyLib lib;

      public void Begin()
      {
          lib = new ThirdPartyLib();
      }

      public void Complete()
      {
          lib.Comlete();
      }

      public void Dispose()
      {
          lib.Dispose();
      }
    }

Then using it:

using (wrapper.Begin()) {

Related posts

Recent Viewed