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]

1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13372정성태6/15/20233109개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233130개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233295개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233092개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233224개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233328오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233130.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232895오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233677.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233240스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233163.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233638오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233033오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233352오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233659.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233769DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233683.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233954.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233566.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234068VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233318오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233645.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233568.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233929.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233775오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...