Decompile Moq generated types using ICSharpCode.Decompiler

154 Views Asked by At

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
0

There are 0 best solutions below