Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 3개 있습니다.)
.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션
; https://www.sysnet.pe.kr/2/0/12210

.NET Framework: 928. .NET Framework의 Strong-named 어셈블리 바인딩 (2) - 런타임에 바인딩 리디렉션
; https://www.sysnet.pe.kr/2/0/12271

.NET Framework: 929. (StrongName의 버전 구분이 필요 없는) .NET Core 어셈블리 바인딩 규칙
; https://www.sysnet.pe.kr/2/0/12272




.NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션

상황을 간단하게 예를 들어 보겠습니다.

가령, ConsoleApp1 (EXE) 프로젝트와 ClassLibrary1 (DLL) 프로젝트에서 Newtonsoft.Json 라이브러리를 다음과 같이 참조해서 사용하면,

ConsoleApp1 (EXE) 프로젝트: Newtonsoft.Json 버전 12.0.0.0 (12.0.3) 참조
ClassLibrary1 (DLL) 프로젝트: Newtonsoft.Json 버전 11.0.0.0 (11.0.2) 참조

이를 실행했을 때 System.IO.FileLoadException 예외가 발생하게 됩니다.

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) at ClassLibrary1.Class1.Test()
at ConsoleApp1.Program.Main(String[] args)


이런 상황은 종종 발생할 수 있으므로 마이크로소프트는 이에 대해 개발자로 하여금 버전 간 호환이 있다고 명시할 수 있는 <bindingRedirect /> 설정을 app.config에 할 수 있도록 지원합니다. 따라서, 위의 예제를 문제없이 실행하려면 ConsoleApp1.exe 프로젝트에 다음과 같은 설정의 app.config을 담고 있어야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="11.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

의미인즉, publicKeyToken == 30ad4fe6b2a6aeed, culture == neutral인 Newtonsoft.Json 어셈블리의 경우 11.0.0.0 ~ 12.0.0.0 버전 범위의 요청이 있으면 그냥 12.0.0.0으로 로드하라는 것입니다. 이 경우 개발자는 적어도 해당 응용 프로그램에서 사용하는 전체적인 Newtonsoft.Json의 기능이 11.0.0.0 ~ 12.0.0.0에서 호환이 가능하다고 CLR에게 알린 것입니다.

물론, 참조하고 있는 어셈블리들이 많아지면 버전 범위를 어디까지 해야 할지 알 수 없는 경우도 있으므로 (하지만, 대개의 경우 현실적으로 귀찮다는 이유 정도로 ^^;) 아예 최종 버전이 하위 호환성을 잘 지키고 있다고 "가정해" 다음과 같이 "0.0.0.0" 시작 범위로 지정하기도 합니다.

<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />

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




사실, 위와 같은 식으로 프로젝트 구성을 하는 경우 Visual Studio는 자동으로 프로젝트들 간 참조 어셈블리의 버전을 파악해 문제가 있음을 알 수 있고 애당초 다음과 같은 식의 컴파일 (에러가 아닌) 경고를 발생시킵니다.

Consider app.config remapping of assembly "Newtonsoft.Json, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" from Version "11.0.0.0" [] to Version "12.0.0.0" [%userprofile%\.nuget\newtonsoft.json\12.0.3\lib\net45\Newtonsoft.Json.dll] to solve conflict and get rid of warning.
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3276: Found conflicts between different versions of the same dependent assembly. Please set the "AutoGenerateBindingRedirects" property to true in the project file. For more information, see http://go.microsoft.com/fwlink/?LinkId=294190.


따라서 MSB3276 경고가 발생하면 app.config에 bindingRedirect를 설정해야 한다는 것을 개발자는 인식할 수 있습니다. 그런데 경고 문구에 보면 AutoGenerateBindingRedirects 옵션을 켜라는 메시지가 보입니다. 이에 따라 .csproj 파일에 다음의 옵션을 추가해 주면,

<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>

프로젝트 빌드 시, 자동으로 app.config에 "0.0.0.0" 버전으로 시작하는 bindingRedirect를 추가해 줍니다. (그러니까, 비주얼 스튜디오 개발자도 귀찮았던 건지도 모릅니다. ^^)

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
    </dependentAssembly>
</assemblyBinding>

혹은, Visual Studio 2017 버전 15.7 이상의 경우 AutoGenerateBindingRedirects 옵션을 프로젝트 속성 창(바인딩 리디렉션 자동 생성)에서도 설정할 수 있습니다.

auto_gen_redirect_1.png

How to: Enable and Disable Automatic Binding Redirection
; https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection

Redirecting Assembly Versions
; https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/redirect-assembly-versions

여기서 하나 더 재미있는 점이 있습니다. 사용자가 만든 어셈블리의 경우에는 저렇게 명시적으로 버전 우회를 하라고 지정해야 하지만, ".NET Framework"에서 배포하는 BCL에 대해서는 버전 명시를 하지 않아도 됩니다. 흔한 예로, .NET 4.0의 ConsoleApp에서 .NET 3.5를 대상으로 만든 ClassLibrary 유형의 어셈블리를 사용하는 데 아무런 문제가 없습니다. 왜냐하면, 지정된 ".NET Framework assemblies"에 한해서는 그와 같은 버전 우회를 CLR이 자동으로 해주기 때문입니다.

Bindings to .NET Framework assemblies are sometimes redirected through a process called assembly unification. The .NET Framework consists of a version of the common language runtime and about two dozen .NET Framework assemblies that make up the type library. These .NET Framework assemblies are treated by the runtime as a single unit. By default, when an app is launched, all references to types in code run by the runtime are directed to .NET Framework assemblies that have the same version number as the runtime that is loaded in a process. The redirections that occur with this model are the default behavior for the runtime.




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

[연관 글]






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

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

비밀번호

댓글 작성자
 



2020-04-21 12시41분
[ryujh] 안녕하세요.
본문의 마지막 줄에서 많이 느끼게 되고 다른 글에서도 주인장님만의 설명에서도 느끼는데
자연적으로 원래 버전 차이가 있을 때 예외발생이 당연한 것을 사용자는 불편하다고 느끼니까 제작사에서는 BCL의 경우 자동화로 편리하게 해준 것인데 사용자는 자동화로 오류가 방지되는 것을 알지 못하는(알 필요없을 수도) 경우군요.
닷넷 아닌 플랫폼에서 일을 하다보면 정말 닷넷이 편리하고 강력하다는 감탄이 듭니다. (닷넷의 무중단 xcopy 배포 등 더 있겠지만 아는대로)
본문의 오류 처리는 dll 백업하고 nuget 라이브러리 자동업데이트 안하도록 했었는데 이 글 보고 많이 도움되었습니다. 그리고 이렇게 글쓰시는 것도 제가 많이 배우게 됩니다. 저도 글을 쓰고 싶은데 그 전에 많이 읽어봐야 겠습니다.
감사합니다.
[guest]

... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13149정성태10/27/20225667오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225658오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224767오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225612.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20225877오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20225716.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226240오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20224983도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20226727.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226097C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20225926.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227218.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/20225604.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/20226176.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/20226406.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
13134정성태10/4/20225138오류 유형: 820. There is a problem with AMD Radeon RX 5600 XT device. For more information, search for 'graphics device driver error code 31'
13133정성태10/4/20225455Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/20225335스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/20227998.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
13130정성태9/28/20225101.NET Framework: 2051. .NET Core/5+ - 에러 로깅을 위한 Middleware가 동작하지 않는 경우파일 다운로드1
13129정성태9/27/20225396.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/20227978C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import파일 다운로드1
13127정성태9/22/20226426Windows: 210. WSL에 systemd 도입
13126정성태9/15/20227031.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
13125정성태9/14/20227243.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
13124정성태9/13/20226986.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...