Code Analysis Warning CA2213 - Call Dispose() on IDisposable backing field

馋奶兔 提交于 2021-02-07 11:18:23

问题


Wanted to post this, even though I figured it out as I was writing the question. Will post answer below.

Getting the following warning with VS Code Analysis:

Warning CA2213 'DBConn' contains field 'DBConn.k__BackingField' that is of IDisposable type: 'SqlConnection'. Change the Dispose method on 'DBConn' to call Dispose or Close on this field.

But my code does call Dispose() on the DBConn property. Does it not on the backing field? I have other instances like this - where I am disposing of where the compiler does not throw this warning. This is the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;    

namespace TheProgramSpace
{
    public sealed class DBConn : IDisposable
    {
        // class containing the database and its connection
        public SqlConnection TheConn { get; }
        public string DbPath { get; }
        public string DbName { get; }


        public DBConn(ProgInstance FPI)
        {
            // constructs new SQLConnection            
            DbPath = FPI.dbPath;
            DbName = FPI.dbName;

            string connString = "Data Source = " + DbPath + "; Initial Catalog =" + DbName + "; Integrated Security = True; "
              + "Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; "
              + "ApplicationIntent = ReadWrite; MultiSubnetFailover = False";                     

            TheConn = new SqlConnection(connString);

        }

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

回答1:


There is not a problem with your code. Dispose will be called on the underlying backing field. This is a known bug in FxCop that surfaced with the introduction of "getter-only" automatic properties which were introduced in C# 6. For now, you can either suppress the warning with an attribute on the class or just ignore it until it's fixed in FxCop.




回答2:


The reason is that TheConn, because it did not have a set accessor, was read-only. Changing the property declaration to

public SqlConnection TheConn { get; private set; }

solved the problem.



来源:https://stackoverflow.com/questions/34583417/code-analysis-warning-ca2213-call-dispose-on-idisposable-backing-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!