Search code examples
c#compilation.net-assembly

Compile C# code dynamically without using original required assemblies


I'm compiling the C# code written by end-user dynamically in my software. In order to compile the code I need to add some assemblies as reference to CompilerParameters.

CompilerParameters loParameters = new CompilerParameters();
loParameters.ReferencedAssemblies.Add("C:\A.dll")
loParameters.ReferencedAssemblies.Add("C:\B.dll")

Therefore I should release these assemblies ("A.dll" and "B.dll") with my software, but because of security reason I don't want the user can access the source of these assemblies by reverse engineering.

Note 1: I can remove the implementation of methods in required assemblies (A and B) but my assemblies are very large and I can't do it manually.

Note 2: I know about obfuscation but I don't want to use that.

Note 3: I just need to compile the code successfully and I don't want to run it.


Solution

  • I assume that the A.dll and B.dll are assemblies that are yours?

    If so, an approach would be to only expose interfaces to these libraries (ie place your interfaces and implementations in separate assemblies) and then ship the interface assemblies.

    This way, there would be nothing to decompile / reverse engineer and it would allow the compiler to be happy.

    To generate said assemblies easily, you could use Roslyn to: remove anything private (fields, properties, methods etc) or unnecessary (static constructors, inline initialisers, etc), replace the body of public methods of public classes with throw new NotImplementedException() for example and compile only that.

    This would then produce assemblies that were merely shells, but effectively exposing correct interfaces which would be sufficient for a compiler.