Skip to content

InvalidProgramException when proxying MemoryStream with .NET 7 #651

@drauch

Description

@drauch

The following repro sample unfortunately fails with the .NET SDK 7.0.200 (it worked like a charm with .NET 6).
I'm using Castle.Core 5.1.1.

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Castle.DynamicProxy;

var xmlString = "<MyXml></MyXml>";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));

var proxyGenerator = new ProxyGenerator();
// THIS IS THE CULPRIT - COMMENTING LINE 12 MAKES IT WORK AGAIN
stream = proxyGenerator.CreateClassProxyWithTarget(stream, new MyInterceptor());

using var reader = XmlReader.Create(stream);
var xdoc = XDocument.Load(reader);
Console.WriteLine(xdoc.Root!.Name);

class MyInterceptor : IInterceptor
{
  public void Intercept (IInvocation invocation)
  {
    invocation.Proceed();
  }
}

The exception is:

Unhandled exception. System.InvalidProgramException: Common Language Runtime detected an invalid program.
at Castle.Proxies.MemoryStreamProxy.Read(Span`1 buffer)
at System.IO.Stream.ReadAtLeastCore(Span`1 buffer, Int32 minimumBytes, Boolean throwOnEndOfStream)
at System.IO.Stream.ReadAtLeast(Span`1 buffer, Int32 minimumBytes, Boolean throwOnEndOfStream)
at System.Xml.XmlTextReaderImpl.InitStreamInput(Uri baseUri, String baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
at System.Xml.XmlTextReaderImpl.FinishInitStream()
at System.Xml.XmlReader.Create(Stream input)
at Program.<Main>$(String[] args) in C:\Projects\ReproInvalidProgramExceptionXmlReader\ReproInvalidProgramExceptionXmlReader\Program.cs:line 13

Please fix this soon, it prevents us from upgrading to .NET 7.

Best regards,
D.R.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions