dotnet / roslyn-analyzers

MIT License
1.6k stars 467 forks source link

CA2213 Diposeable not disposed #7462

Closed CoolCoderSuper closed 3 weeks ago

CoolCoderSuper commented 3 weeks ago

Analyzer

Diagnostic ID: CA2213: Disposeable field not disposed

Describe the bug

Steps To Reproduce

Public NotInheritable Class OllamaChatProvider
    Implements IDisposable

    Private ReadOnly m_objClient As OllamaApiClient

    Public Sub New(strURL As String, strModel As String)
        m_objClient = New OllamaApiClient(New Uri(strURL))
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        m_objClient.Dispose()
    End Sub
End Class

Expected behavior

I would assume that it would no longer give the warning since it is diposed.

Actual behavior

It gives the warning.

Additional context

I don't quite understand what triggers it since this works:

Public NotInheritable Class A
    Implements ITest1, IDisposable
    Public Sub New(c As Uri)

    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
    End Sub
End Class

Public NotInheritable Class B
    Implements IDisposable

    Private ReadOnly a As A
    Public Sub New(c As String)
        a = New A(New Uri(c))
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        a.Dispose()
    End Sub
End Class

Public Interface ITest1
    Inherits IDisposable
End Interface

It only ever breaks when using the OllamaApiClient type from OllamaSharp. As soon I change it to say explicitly IDisposable it works.

    Private ReadOnly m_objClient As IDisposable

    Public Sub New(strURL As String, strModel As String)
        m_objClient = New OllamaApiClient(New Uri(strURL))
    End Sub
CoolCoderSuper commented 3 weeks ago

So I figured out how to reproduce it.

Public Class A
    Implements ITest1, IDisposable

    Public Sub New(c As Uri)

    End Sub
    Public Sub Dispose()
    End Sub
    Public Sub DifferentDispose() Implements IDisposable.Dispose
        Dispose()
    End Sub
End Class

Public NotInheritable Class B
    Implements IDisposable

    Private ReadOnly a As A

    Public Sub New(c As String, d As String)
        a = New A(New Uri(c))
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        a.Dispose()
    End Sub
End Class

Public Interface ITest1
    Inherits IDisposable
End Interface

The bad code from OllamaSharp

   //
   // Summary:
   //     Releases the resources used by the OllamaSharp.OllamaApiClient instance. Disposes
   //     the internal HTTP client if it was created internally.
   public void Dispose()
   {
       if (_disposeHttpClient)
       {
           _client?.Dispose();
       }
   }

   void IDisposable.Dispose()
   {
       Dispose();
   }

I assume this should be fixed there.