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)
13449정성태11/21/20232351개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232626닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232486닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232419닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232699Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232454닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232492개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232321개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232652닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232352Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232843닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232462닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232656닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232893닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232828닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232618스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232341스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232378오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232707스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232597닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232856닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232918닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233085닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233268스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233084닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233063스크립트: 58. 파이썬 - async/await 기본 사용법
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...