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)
13550정성태2/11/20242107Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242477개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242308개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242055개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241896Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241827닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241846오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241824Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241875오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241921VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242050Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242144개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242213닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242264닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242372닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242206닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242038닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242232닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242141닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242023닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242010닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241893닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242032Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241959오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242047닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242015오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...