Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

.NET Core/5+에서 C# 코드를 동적으로 컴파일/사용하는 방법

현재, .NET Core/5+에서 CodeDomProvider는 사용할 수 없습니다. 그런데 이유는 알 수 없지만, "System.CodeDom" 어셈블리를 .NET Core/5+ 프로젝트에서 참조할 수 있게 제한을 풀었기 때문에 nuget으로 설치는 됩니다.

Install-Package System.CodeDom

/*
.NETFramework 4.6.1
    No dependencies.
.NETStandard 2.0
    No dependencies.
*/

하지만 실제로 사용해 보면,

using System.CodeDom.Compiler;

string srcContents = System.IO.File.ReadAllText("dynamic_code.txt");

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerInfo langCompilerInfo = CodeDomProvider.GetCompilerInfo("CSharp");

System.CodeDom.Compiler.CompilerParameters parameters = langCompilerInfo.CreateDefaultCompilerParameters();

parameters.IncludeDebugInformation = true;
parameters.CompilerOptions = "/define:DEBUG;TRACE";

codeProvider.CompileAssemblyFromSource(parameters, srcContents);

PlatformNotSupportedException 예외가 발생합니다.

Unhandled exception. System.PlatformNotSupportedException: Operation is not supported on this platform.
   at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) in System.CodeDom.dll:token 0x600059e+0x5
   at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources) in System.CodeDom.dll:token 0x6000597+0x8f
   at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources) in System.CodeDom.dll:token 0x600058f+0xf
   at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources) in System.CodeDom.dll:token 0x60002e5+0x0
   at <Program>$.<Main>$(String[] args)

검색해 보면, "Microsoft.CodeDom.Providers.DotNetCompilerPlatform"을 사용해 보라고도 하는데, 이것은 .NET Framework에서만 설치되므로 .NET Core/5+에서는 사용 자체가 안 됩니다.




어쩔 수 없습니다. Rosyln과 연동하는 Microsoft.CodeAnalysis.CSharp을 사용해,

Install-Package Microsoft.CodeAnalysis.CSharp

다음의 예제에서처럼,

joelmartinez/dotnet-core-roslyn-sample
; https://github.com/joelmartinez/dotnet-core-roslyn-sample/blob/master/Program.cs

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string codeToCompile = @"
using System;
using System.Text;

public class MyType
{
    public void Print(object obj)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(
            DateTime.Now
        );

        Console.WriteLine(""Hello: "" + obj + "" : "" + sb.ToString());
    }
}
";
            string assemblyName = "MyAssembly";

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile);

            var refPaths = new[] {
                typeof(System.Object).GetTypeInfo().Assembly.Location,
                typeof(Console).GetTypeInfo().Assembly.Location,
                Path.Combine(Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.Location), "System.Runtime.dll")
            };
            MetadataReference[] references = refPaths.Select(r => MetadataReference.CreateFromFile(r)).ToArray();

            CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: options);

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);

                    Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
                    var type = assembly.GetType("MyType");
                    var instance = assembly.CreateInstance("MyType");
                    var meth = type.GetMember("Print").First() as MethodInfo;
                    meth.Invoke(instance, new[] { "World" });
                }
            }
        }
    }
}

소스 코드로부터 동적으로 컴파일을 해 어셈블리를 얻을 수 있습니다. 따라서, 만약 .NET Framework/.NET Core/5+를 지원해야 하는 공통 소스 코드가 있다면 동적 컴파일 부분만큼은 별도의 클래스를 사용하도록 나눠야 합니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/26/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-06-08 09시34분
정성태

1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...
NoWriterDateCnt.TitleFile(s)
13270정성태2/24/20233755.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234290스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20234842개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234770.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234371오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234285.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20235769스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20233893개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20234986디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234279Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234067오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234196.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234104오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234196.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235045개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234343오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/20234251Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20234990Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20233820오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234298스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236100오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20234906오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234044오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20234961VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234073개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234618.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...