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)
13475정성태12/7/20232280닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232136개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232326닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232155C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232184Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232486닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232195닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232190닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232202오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232396닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232152개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232273닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232216오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232251오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232270닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232225닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232207닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232213닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232165VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232461닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232339닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232683닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232218오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232296닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232431닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232255닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...