Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing of X509Chain

Tags:

c#

.net

In Visual Studio 2013 targeting .NET Framework 4.5.1, I find that disposing of an X509Chain is more difficult than expected. According to the MSDN documentation, starting in 4.5 X509Chain is disposable. The reference source confirms it, and looking at the class with ildasm also confirms it:

X509Chain in ildasm

And yet, when attempting to put it in a using statement like so:

using (var chain = new X509Chain())
{

}

I get a compilation error:

Error 1 'System.Security.Cryptography.X509Certificates.X509Chain': type used in a using statement must be implicitly convertible to 'System.IDisposable'

More confusingly, Visual Studio's definition of the class says that it isn't IDisposable.

However, if at run time I do this:

var chain = new X509Chain();
try
{

}
finally
{
    var disposable = chain as IDisposable;
    if (disposable != null)
    {
        disposable.Dispose();
    }
}

Indeed, the cast to IDisposable will succeed, and dispose will get called.

I think the issue is because the reference assembly in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5.1 does not implement IDisposable even though the actual assembly used at run time does.

Is there a way I can cleanly dispose of an X509Chain without having to do the try/finally and cast myself, i.e. can I get it working in a using statement? I suppose I could wrap the class myself, but I'd prefer not to introduce a new type, I'd rather get the compiler to do the work for me.

It appears that the reference assembly has the same issue in 4.5.2, however it is fixed in 4.6, but moving to 4.6 is not on the radar right now.

like image 629
vcsjones Avatar asked Aug 03 '15 16:08

vcsjones


1 Answers

I got a response from Microsoft on this (thanks Microsoft!).

It turns out this is new in the .NET 4.6 Framework, the MSDN documentation does not yet separate changes from 4.5 to 4.6 into separate sections and the pages do not specifically mention this.

I also made the mistake of having the .NET 4.6 framework installed locally - which means the actual assembly at runtime was 4.6. Had I been on an environment that was 4.5 only I would have seen that the cast failed and dispose would never have been called.

like image 199
vcsjones Avatar answered Oct 13 '22 04:10

vcsjones