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)
13708정성태8/7/202413163개발 환경 구성: 719. ffmpeg / YoutubeExplode - mp4 동영상 파일로부터 Audio 파일 추출
13707정성태8/6/202412731닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상파일 다운로드1
13706정성태8/5/202411975개발 환경 구성: 718. Hyper-V - 리눅스 VM에 새로운 디스크 추가
13705정성태8/4/202412351닷넷: 2291. C# 13 - (5) params 인자 타입으로 컬렉션 허용 [2]파일 다운로드1
13704정성태8/2/202414037닷넷: 2290. C# - 간이 dotnet-dump 프로그램 만들기파일 다운로드1
13703정성태8/1/202412202닷넷: 2289. "dotnet-dump ps" 명령어가 닷넷 프로세스를 찾는 방법
13702정성태7/31/202413543닷넷: 2288. Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완파일 다운로드1
13701정성태7/30/202414699닷넷: 2287. C# 13 - (4) Indexer를 이용한 개체 초기화 구문에서 System.Index 연산자 허용파일 다운로드1
13700정성태7/29/202414088디버깅 기술: 200. DLL Export/Import의 Hint 의미
13699정성태7/27/202414689닷넷: 2286. C# 13 - (3) Monitor를 대체할 Lock 타입파일 다운로드1
13698정성태7/27/202413542닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리파일 다운로드1
13697정성태7/26/202412083닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/202412661오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/202412459닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/202412362닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/202411808개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/202413827디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/202412648디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/202410859오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/202414633디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/202411818닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/202413622닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/202413038오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
13685정성태7/19/202412504스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
13684정성태7/19/202413395닷넷: 2279. C# - 문자열 보간식 사례 (예: 조건 연산자 사용)
13683정성태7/18/202411877오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...