Skip to content

Code-gen shouldDispose ctor and Dispose pattern #1971

Description

@krwq

Almost all device bindings have _i2cDevice, _spiDevice and very similar Dispose code. Some of them provide shouldDispose flag. My suggestion is that we automate this part where possible:

  • we create source generator (new roslyn feature)
  • we remove explicit shouldDispose handling and replace that with generated code

for example

[GenerateDisposePattern] // whatever name, not much important
public partial class SomeDevice : IDisposable
{
  public SomeDevice(I2cDevice device, <some-other-args-but-nothing-related-to-disposing>)
  {
     //...
  }
}

generated code:

public partial class SomeDevice : IDisposable
{
  private bool _shouldDispose = true; // default based on majority of current implementation
  public SomeDevice(I2cDevice device, <some-other-args-but-nothing-related-to-disposing>, bool shouldDispose)
    : this(device, ....)
  {
    _shouldDispose = shouldDispose;
  }

  public void Dispose()
  {
     if (_shouldDispose)
     {
        // proper implementation, we pick member of type `I2cDevice`, `SpiDevice` etc
     }
  }
}

Related issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Priority:2Work that is important, but not critical for the releaseStatus: In PRenhancementNew feature or request

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions