0

I am interested in decompiling Moq generated types using ICSharpCode.Decompiler to see what they look like. But I am getting an error because Moq uses dynamic assembly and apparently it's not supported. I am just very curious what Moq implementation looks like.

using System.Reflection;
using System.Reflection.PortableExecutable;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using Moq;

public record TestModel;

internal class Program
{
    public static void Main(string[] args)
    {
        foreach (var type in new [] { typeof(TestModel), new Mock<TestModel>().Object.GetType() })
        {
            Assembly currentAssembly = type.Assembly;

            var assemblyResolver = new UniversalAssemblyResolver(currentAssembly.Location, false, null);
            var module = new PEFile(currentAssembly.Location, PEStreamOptions.PrefetchEntireImage);
            var decompilerTypeSystem = new DecompilerTypeSystem(module, assemblyResolver);

            var decompilerSettings = new DecompilerSettings();
            var decompiler = new CSharpDecompiler(currentAssembly.Location, assemblyResolver, decompilerSettings);
            
            var typeDefinition = decompilerTypeSystem.MainModule.GetTypeDefinition(new FullTypeName(type.FullName));
            var decompiledCode = decompiler.DecompileAsString(typeDefinition.MetadataToken);
            Console.WriteLine(decompiledCode);
        }
    }
}

csproj

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="ICSharpCode.Decompiler" Version="8.1.0.7455" />
      <PackageReference Include="Moq" Version="4.18.4" />
    </ItemGroup>

</Project>

Error:

Unhandled exception. System.NotSupportedException: The invoked member is not supported in a dynamic assembly.
   at System.Reflection.Emit.InternalAssemblyBuilder.get_Location()
   at Program.Main(String[] args) in /home/amir/workspace/ConsoleApp1/ConsoleApp1/Program.cs:line 19
Node.JS
  • 1,042
  • 6
  • 44
  • 114
  • Uhm, Moq source is just available on GitHub.... You can just use the source code in your project. Actually: what are you expecting? – JHBonarius Aug 07 '23 at 12:43
  • as I know there is no straightforward solution to decompile Moq-generated types using ICSharpCode.Decompiler. because `Moq` uses dynamic assemblies, the decompiler cannot access the necessary metadata and assembly information to decompile the types! – Freeman Aug 14 '23 at 10:21

0 Answers0