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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  [56]  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12650정성태5/17/202121860기타: 82. OpenTabletDriver의 버튼에 더블 클릭을 매핑 및 게임에서의 지원 방법
12649정성태5/16/202122822.NET Framework: 1059. 세대 별 GC(Garbage Collection) 방식에서 Card table의 사용 의미 [1]
12648정성태5/16/202123237사물인터넷: 66. PC -> FTDI -> NodeMCU v1 ESP8266 기기를 UART 핀을 연결해 직렬 통신하는 방법파일 다운로드1
12647정성태5/15/202120469.NET Framework: 1058. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용파일 다운로드1
12646정성태5/15/202119916사물인터넷: 65. C# - Arduino IDE의 Serial Monitor 기능 구현파일 다운로드1
12645정성태5/14/202119695사물인터넷: 64. NodeMCU v1 ESP8266 - LittleFS를 이용한 와이파이 접속 정보 업데이트파일 다운로드1
12644정성태5/14/202122933오류 유형: 719. 윈도우 - 제어판의 "프로그램 및 기능" / "Windows 기능 켜기/끄기" 오류 0x800736B3
12643정성태5/14/202123251오류 유형: 718. 서버 유형의 COM+ 사용 시 0x80080005(Server execution failed) 오류 발생
12642정성태5/14/202124047오류 유형: 717. The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
12641정성태5/13/202122877디버깅 기술: 179. 윈도우용 .NET Core 3 이상에서 Windbg의 sos 사용법
12640정성태5/13/202127966오류 유형: 716. RDP 연결 - Because of a protocol error (code: 0x112f), the remote session will be disconnected. [1]
12639정성태5/12/202123712오류 유형: 715. Arduino: Open Serial Monitor - The module '...\detection.node' was compiled against a different Node.js version using NODE_MODULE_VERSION
12638정성태5/12/202121569사물인터넷: 63. NodeMCU v1 ESP8266 - 펌웨어 내 파일 시스템(SPIFFS, LittleFS) 및 EEPROM 활용
12637정성태5/10/202123393사물인터넷: 62. NodeMCU v1 ESP8266 보드의 A0 핀에 다중 아날로그 센서 연결 [1]
12636정성태5/10/202124618사물인터넷: 61. NodeMCU v1 ESP8266 보드의 A0 핀 사용법 - FSR-402 아날로그 압력 센서 연동파일 다운로드1
12635정성태5/9/202120732기타: 81. OpenTabletDriver를 (관리자 권한으로 실행하지 않고도) 관리자 권한의 프로그램에서 동작하게 만드는 방법
12634정성태5/9/202118328개발 환경 구성: 572. .NET에서의 필수 무결성 제어 - 외부 Manifest 파일을 두는 방법파일 다운로드1
12633정성태5/7/202123952개발 환경 구성: 571. UAC - 관리자 권한 없이 UIPI 제약을 없애는 방법
12632정성태5/7/202124280기타: 80. (WACOM도 지원하는) Tablet 공통 디바이스 드라이버 - OpenTabletDriver
12631정성태5/5/202123528사물인터넷: 60. ThingSpeak 사물인터넷 플랫폼에 ESP8266 NodeMCU v1 + 조도 센서 장비 연동파일 다운로드1
12630정성태5/5/202124846사물인터넷: 59. NodeMCU v1 ESP8266 보드의 A0 핀 사용법 - CdS Cell(GL3526) 조도 센서 연동파일 다운로드1
12629정성태5/5/202126983.NET Framework: 1057. C# - CoAP 서버 및 클라이언트 제작 (UDP 소켓 통신) [1]파일 다운로드1
12628정성태5/4/202123850Linux: 39. Eclipse 원격 디버깅 - Cannot run program "gdb": Launching failed
12627정성태5/4/202123266Linux: 38. 라즈베리 파이 제로 용 프로그램 개발을 위한 Eclipse C/C++ 윈도우 환경 설정
12626정성태5/3/202124178.NET Framework: 1056. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상 (2)파일 다운로드1
12625정성태5/3/202121112오류 유형: 714. error CS5001: Program does not contain a static 'Main' method suitable for an entry point
... 46  47  48  49  50  51  52  53  54  55  [56]  57  58  59  60  ...