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)
13908정성태4/2/20258386닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20258837VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20258306닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20258320Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20257710디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20257656VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20257361개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20257739Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20259954스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20256502스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20257087오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20258999닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20259052Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20258717Linux: 117. eBPF (bpf2go) - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20257815Linux: 116. eBPF (bpf2go) - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20256928Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
13892정성태2/24/202510127닷넷: 2325. C# - PowerShell과 연동하는 방법파일 다운로드1
13891정성태2/23/20257464닷넷: 2324. C# - 프로세스의 성능 카운터용 인스턴스 이름을 구하는 방법파일 다운로드1
13890정성태2/21/20258433닷넷: 2323. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(Win32 API)파일 다운로드1
13889정성태2/20/20259417닷넷: 2322. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(성능 카운터, WMI) [1]파일 다운로드1
13888정성태2/17/20259761닷넷: 2321. Blazor에서 발생할 수 있는 async void 메서드의 부작용
13887정성태2/17/202511543닷넷: 2320. Blazor의 razor 페이지에서 code-behind 파일로 코드를 분리 및 DI 사용법
13886정성태2/15/20257109VS.NET IDE: 196. Visual Studio - Code-behind처럼 cs 파일을 그룹핑하는 방법
13885정성태2/14/20259336닷넷: 2319. ASP.NET Core Web API / Razor 페이지에서 발생할 수 있는 async void 메서드의 부작용
13884정성태2/13/202511094닷넷: 2318. C# - (async Task가 아닌) async void 사용 시의 부작용파일 다운로드1
13883정성태2/12/20259787닷넷: 2317. C# - Memory Mapped I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...