Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

C# - dynamic 예약어 사용 시 런타임에 "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" 예외가 발생하는 경우

MongoDB C# 드라이버를 사용하다가 겪은 재미있는 현상에 대해 이야기해 보겠습니다. 우선, 문제를 재현하는 코드 먼저 보면 더 좋겠지요. ^^

using MongoDB.Driver;

namespace ConsoleApp1;

internal class Program
{
    // Install-Package MongoDB.Driver
    static void Main(string[] args)
    {
        string connectionString = "mongodb://192.168.0.8:27017/";
        var client = new MongoClient(connectionString);
        var db = client.GetDatabase("MYTESTDB");

        // It's OK
        Console.WriteLine(db.Client);

        // Throws an exceoption: Unhandled exception. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Client'
        dynamic dbInstance = db;
        Console.WriteLine(dbInstance.Client);
    }
}

첫 번째 접근은 당연히 오류 없이 실행되는데요, 문제는 두 번째처럼 dynamic으로 변환한 후에 Client 프로퍼티를 접근하는 경우 다음과 같이 예외가 발생합니다.

cs_dynamic_binder_failure_1.png

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
  HResult=0x80131500
  Message='object' does not contain a definition for 'Client'
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

이때의 "Output" 창의 메시지는 이런데요,

Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in System.Linq.Expressions.dll
An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Linq.Expressions.dll
'object' does not contain a definition for 'Client'

가만 보면, 이상한 점이 하나 눈에 띕니다. 바로 Client 프로퍼티를 가지고 있는 개체를 object로 인식하고 있다는 건데, 사실 런타임에 담긴 값은 결국 "MongoDB.Driver.MongoDatabase" 타입의 인스턴스이기 때문에 화면의 메시지에는 'object'가 아닌 'MongoDatabase'라고 나와야 할 것입니다.

비교를 위해 다음과 같은 예제로 코딩하면,

{
    string text = "TEST";
    dynamic dynText = text;
    Console.WriteLine(dynText.ToUpperTest()); // Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''string' does not contain a definition for 'ToUpperTest''
}

이번에는 '타입' 위치에 "string"이라고 올바른 타입 이름을 명시하고 있습니다. 즉, dbInstance.Client에서의 오류 원인은 해당 타입의 인식을 'System.Object'로 잘못 판단하고 있기 때문입니다.




저 문제는, C# 컴파일러가 dynamic을 사용할 때 작성해 주는 코드를 직접 사용해 재현하는 것도 가능합니다.

object dbInstance = db;

CallSite<Func<CallSite, object, object>>? p0 = CallSite<Func<CallSite, object, object>>.Create(
    Binder.GetMember(CSharpBinderFlags.None, "Client", typeof(Program), new CSharpArgumentInfo[]
    {
            CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
    }));

object? result = p0.Target(p0, dbInstance); // 여기서 RuntimeBinderException 발생
Console.WriteLine(result);

이렇게 되면, 문제를 우회 해결하는 것이 가능한데요, 바로 Binder.GetMember의 세 번째 인자인 'context'에 typeof(Program) 대신에 직접 원본 타입 정보를 넘겨주는 것입니다.

Type type = db.GetType();

CallSite<Func<CallSite, object, object>>? p0 = CallSite<Func<CallSite, object, object>>.Create(
    Binder.GetMember(CSharpBinderFlags.None, "Client", type, new CSharpArgumentInfo[]
    {
            CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
    }));

저렇게 바꾸고 나면 더 이상 예외 없이, 정상적으로 Client 프로퍼티에 접근할 수 있습니다.




문서상으로는, Binder.GetMember의 세 번째 인자인 'context'는 "The Type that indicates where this operation is used."라고 해서 "Client" 속성을 가진 타입 정보를 넘겨줘야 하는 것처럼 명시하고 있는데요, 하지만 문제가 없는 dynamic 코드를 위의 예제에 추가해 테스트해 보면 그 자리에 typeof(Program) 값이 넘어가는 것을 볼 수 있습니다. 그런 의미에서, 꼭 원본 타입 정보를 넘겨줘야 할 필요는 없어 보입니다.

예를 들어, 위에서 db.Client 대신 db.Settings로부터 dynamic 호출을 해 보면,

dynamic dbInstance = db.Settings;
ReadPreference clnt = dbInstance.ReadPreference;
Console.WriteLine(clnt);

이것 역시 C# 컴파일러가 생성한 코드를 보면 typeof(Program)이 사용되고 있지만,

var p0 = CallSite<Func<CallSite, object, object>>.Create(
    Binder.GetMember(CSharpBinderFlags.None, "ReadPreference", typeof(Program), new CSharpArgumentInfo[]
    {
        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
    }));

정상적으로 동작합니다. 뭔가 저 2개의 정상/비정상 사이에 규칙이 있을 것도 같은데 제 수준에서는 잘 모르겠습니다. ^^;

참고로, 문제가 있던 코드의 경우 context에 원본 타입 정보를 넘겨주는 것이 가장 안전하겠지만, 좀 더 테스트를 해보면 그것뿐만 아니라 그냥 원본 타입이 정의된 어셈블리의 아무 타입이나 넘겨줘도 상관은 없었습니다. 즉, 다음과 같이 전혀 다른 타입이지만 MongoDB.Driver 어셈블리에 정의된 아무 타입이나 넘겨줘도 잘 실행이 됩니다.

Type type = typeof(MongoDB.Driver.AggregateBucketAutoGranularity);

CallSite<Func<CallSite, object, object>>? p0 = CallSite<Func<CallSite, object, object>>.Create(
    Binder.GetMember(CSharpBinderFlags.None, "Client", type, new CSharpArgumentInfo[]
    {
        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
    }));

일단 오늘은 여기까지만 정리하고, 나머지는 다음 편에 이어서 ^^ 다루도록 하겠습니다.

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




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







[최초 등록일: ]
[최종 수정일: 10/21/2025]

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

비밀번호

댓글 작성자
 




1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13983정성태8/4/20254164오류 유형: 972. Microsoft.Data.SqlClient 6.1.0 버전부터 .NET 8 이상만 지원
13982정성태8/2/20254859개발 환경 구성: 753. CentOS 7 컨테이너 내에서 openssh 서버 호스팅
13981정성태8/1/20254166오류 유형: 971. CentOS 7에서 yum 사용 시 "Could not resolve host: mirrorlist.centos.org; Unknown error"
13980정성태7/31/20254361Linux: 119. eBPF - BPF_PROG_TYPE_CGROUP_SOCK 유형에서 정상 동작하지 않는 BPF_CORE_READ (2)
13979정성태7/30/20255242Linux: 118. eBPF - BPF_PROG_TYPE_CGROUP_SOCK 유형에서 정상 동작하지 않는 BPF_CORE_READ
13978정성태7/29/20254199오류 유형: 970. 파일 복사 시 "Data error (cyclic redundancy check). (0x80070017)" 에러
13977정성태7/28/20255198닷넷: 2349. C# 14 - (4) 문자열 리터럴을 utf-8 인코딩으로 저장파일 다운로드1
13976정성태7/25/20254180닷넷: 2348. C# - 카카오 카나나 모델 + Microsoft.ML.OnnxRuntimeGenAI 예제파일 다운로드1
13975정성태7/23/20254407닷넷: 2347. C# 14 - (3) 형식 인자가 없는 제네릭 타입의 nameof 지원파일 다운로드1
13974정성태7/22/20254344닷넷: 2346. C# 14 - (2) Span 타입과 배열 간의 암시적 형변환파일 다운로드1
13973정성태7/21/20254806닷넷: 2345. C# - 배열 및 Span의 공변성파일 다운로드1
13972정성태7/21/20254245닷넷: 2344. C#의 Identity conversion 의미파일 다운로드1
13971정성태7/17/20254614닷넷: 2343. C# 14 - (1) 속성 구문에서 문맥 키워드로 추가되는 field 예약어파일 다운로드1
13970정성태7/17/20254205닷넷: 2342. C# 14 - (취소된 글)
13969정성태7/17/20254242닷넷: 2341. snap으로 설치한 .NET 리눅스 실행 환경
13968정성태7/16/20254316오류 유형: 969. lddtree - TypeError: 'type' object is not subscriptable
13967정성태7/16/20255338오류 유형: 968. snap으로 설치한 "dotnet run" 실행 시 "undefined symbol: _dl_audit_symbind_alt, version GLIBC_PRIVATE" 오류
13966정성태7/15/20255967디버깅 기술: 223. WinDbg - .kframes 명령어
13965정성태7/11/20254891오류 유형: 967. 디버깅 모드로 실행 시 "Could not find file 'C:\Program Files\IIS Express\Oracle.DataAccess.Common.Configuration.Section.xsd'" 예외
13964정성태7/10/20256445닷넷: 2340. C# - Win32 Multimedia Timer 주기파일 다운로드1
13963정성태7/8/20255976VS.NET IDE: 202. Visual Studio 2022 + Copilot 기본 사용법
13962정성태7/7/20255148스크립트: 79. 파이썬 - onnxruntime_genai에서 지원하지 않는 모델 사용
13961정성태7/5/20255144디버깅 기술: 222. WinDbg 분석 사례 - IISreset 시점에 w3wp.exe의 crash 발생
13960정성태7/3/20255722개발 환경 구성: 752. ProcDump - C/C++ 예외 코드 필터를 지정한 덤프 생성 [2]
13959정성태6/25/20254922오류 유형: 966. Ubuntu - ping: connect: Network is unreachable
13958정성태6/21/20255688닷넷: 2339. C# - Phi-4-multimodal 모델의 GPU 가속 방법 (ORT 사용)파일 다운로드1
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...