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)
14008정성태8/26/20254740닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20255121닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20255399Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20254378오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20255037오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20255369닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
14002정성태8/20/20255394오류 유형: 980. C# - appsettings.json 파일의 설정값이 적용 안 된다면?
14001정성태8/19/202510205닷넷: 2356. .NET SDK 10 - 단일 소스 코드 파일을 빌드/실행하는 기능을 "dotnet" 명령어에 추가 [1]
14000정성태8/18/20255754오류 유형: 979. ERROR: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
13999정성태8/15/20255305닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능파일 다운로드1
13998정성태8/14/20254780닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가파일 다운로드1
13997정성태8/14/20255844Linux: 120. docker 컨테이너로 매핑된 볼륨에 컨테이너 측의 사용자 ID를 유지하면서 복사하는 방법
13996정성태8/13/20254473오류 유형: 978. Unable to find the requested .Net Framework Data Provider.
13995정성태8/13/20254767개발 환경 구성: 754. Visual C++ - 리눅스 빌드를 위한 Ubuntu 18 docker 컨테이너 설정
13994정성태8/12/20254281오류 유형: 977. SQL Server - User, group, or role '...' already exists in the current database. (Microsoft SQL Server, Error: 15023)
13993정성태8/11/20255371오류 유형: 976. Microsoft.ML.OnnxRuntimeGenAI 패키지 사용 시 "cublasLt64_12.dll" which is missing. (Error 126: "The specified module could not be found.") 오류
13992정성태8/11/20255030닷넷: 2353. C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용파일 다운로드1
13991정성태8/9/20254849오류 유형: 975. winget - Foundry Local 패키지 업데이트가 안 되는 문제
13990정성태8/8/20254120Windows: 283. Time zone 설정이 없는 Windows Server 2025
13989정성태8/8/20255477닷넷: 2352. C# - Windows S-mode 환경인지 체크하는 방법파일 다운로드1
13988정성태8/8/20255189오류 유형: 974. 비주얼 스튜디오 업데이트 시 잠김 파일 경고 - Visual Studio Standard Collector Service 150 (VSStandardCollectorService150)
13987정성태8/7/20254764닷넷: 2351. C# 14 - (6) event와 생성자에도 partial 메서드 적용파일 다운로드1
13986정성태8/6/20253910닷넷: 2350. C# 14 - (5) 람다 매개 변수에 접근자가 있는 경우에도 타입 생략 가능파일 다운로드1
13985정성태8/6/20255013오류 유형: 973. "wsl --install" 명령어 수행 시 "The server name or address could not be resolved"
13984정성태8/6/20254553Windows: 282. 윈도우 운영체제에 추가된 ssh 서버(Win32-OpenSSH)
13983정성태8/4/20254164오류 유형: 972. Microsoft.Data.SqlClient 6.1.0 버전부터 .NET 8 이상만 지원
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...