Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

ASP.NET에서 Server.CreateObject와 COM Interop 클래스 생성의 차이점

COM 개체를 Visual Studio에서 참조 추가하면 일반적으로 Interop.[파일명].dll 형식의 파일이 생성됩니다. 이 파일에는 COM의 IDL로 표현된 정보들과 Visual Studio가 임의로 만든 COM 개체 생성 코드들이 함께 들어가 있습니다.

Visual Studio 2010 부터는 COM Interop DLL에서 COM 개체 생성 코드를 제거하는 방법이 제공됩니다. 이런 경우, 인터페이스 정의만 Interop DLL이 포함하게 됩니다. 여기에 맞물려 .NET 4.0부터는 "Embed Interop Types" 기능이 제공되어 굳이 Interop DLL (보다 정확히 말하면 PIA - Primary Interop Assemblies) 자체를 어셈블리 내부에 포함하는 기능이 있어서 배포시 Interop DLL을 제외시켜도 됩니다.

아래의 화면은 "WebTestHelperLib" COM 개체 참조의 "Embed Interop Types" 설정을 보여줍니다.

server_create_object_1.png

이렇게 된 경우, 당연히 다음과 같은 코드는 유효하지 않습니다.

WebTestHelperLib.ComAptTestClass catc = new WebTestHelperLib.ComAptTestClass();

왜냐하면, "Embed Interop Types" == True 설정으로 인해 [...]Class에 대한 코드가 Interop DLL에 제외되었고 심지어 그 DLL의 배포조차도 제외된 상태이기 때문에 컴파일 시에 다음과 같은 오류가 발생합니다.

Interop type '...Class' cannot be embedded. Use the applicable interface instead.   d:\...\WebApplication1\Default.aspx.cs

Visual Studio 2010부터 COM 개체 참조시 기본값으로 "Embed Interop Types" == True가 설정되기 때문에 위와 같은 오류를 제법 많이 볼 수 있습니다. 따라서 이런 오류가 발생할 때는 "Embed Interop Types" == False로 설정하면 해결됩니다.

아래는 그에 대한 몇가지 사례입니다.

.NET에서 WAV, MP3 파일 재생하는 방법
; https://www.sysnet.pe.kr/2/0/1217

Microsoft PowerPoint 슬라이드를 HTML 파일로 ".files" 폴더 없이 저장하는 방법 (C# 코드)
; https://www.sysnet.pe.kr/2/0/1219




사실 "Embed Interop Types" == True인 상황에서 [...]Class가 없더라도 해당 COM 개체를 생성할 수 있습니다. 이런 경우에 Activator를 사용하면 되는데요. 이에 대해서도 지난번에 설명을 했었습니다.

레지스트리 등록 및 Interop DLL 없이 COM 개체 사용하는 방법
; https://www.sysnet.pe.kr/2/0/1180

위의 방법은 .NET 4.0 미만에서도 사용할 수 있지만 "Embed Interop Types" == True 기능으로 인해 4.0에서 굳이 Interface 정의를 수작업으로 배낄 필요가 없어졌다는 차이가 있습니다.

따라서 해당 COM 개체의 CLSID 값만 알고 있다면 다음과 같이 쉽게 COM 개체를 생성할 수 있습니다.

Type type = Type.GetTypeFromCLSID(new Guid("{48D11CC5-C50A-403D-A4AC-0825A56E5C13}"));
WebTestHelperLib.IComAptTest catc = Activator.CreateInstance(type) as WebTestHelperLib.IComAptTest;

그런데, ASP.NET에는 COM 개체를 생성하기 위한 또 다른 방법이 제공됩니다. 기존 ASP와의 호환으로 인해 Server.CreateObject를 동일하게 사용할 수 있는데, 실제로 System.Web.UI.Page 개체는 Server 속성을 제공해 주므로 다음과 같이 COM 개체를 생성할 수 있습니다.

protected void Page_Load(object sender, EventArgs e)
{
    WebTestHelperLib.IComAptTest catc = 
        Server.CreateObjectFromClsid("{48D11CC5-C50A-403D-A4AC-0825A56E5C13}") as WebTestHelperLib.IComAptTest;

    // ...[생략]...
}

재미있는 것은 Server.CreateObject 는 몇 가지 안전 장치가 추가되었다는 점입니다.

Server.CreateObject는 STA COM 개체를 생성하는 경우 반드시 AspCompat=True인 상황에서만 동작한다는 강제성을 가지고 있습니다. 이 때문에 aspx에 <%@ Page AspCompat=True %>로 설정된 상황이라고 해도 STA COM 개체를 ASP.NET Page 개체의 생성자에서 만들려고 하면 예외가 발생합니다. 즉, 다음과 같은 코드는 x86/x64 모두에서 오류가 발생합니다.

public partial class _Default : System.Web.UI.Page
{
    WebTestHelperLib.IComAptTest catc;

    public _Default()
    {
        catc = Server.CreateObjectFromClsid("{48D11CC5-C50A-403D-A4AC-0825A56E5C13}") 
            as WebTestHelperLib.IComAptTest;
    }
}

// 예외 발생: The component '{...}' cannot be created.  Apartment threaded components can only be created on pages with an <%@ Page aspcompat=true %> page directive. 

따라서, STA COM개체를 생성하는 Server.CreateObject는 반드시 Page_Load 이벤트 이후에서만 사용할 수 있습니다.

그 외에 또 다른 차이점이라면 Server.CreateObject로 생성된 STA COM 개체는 자동으로 해제된다는 특징이 있습니다. AspCompat=True인 경우의 콜 스택을 볼까요?

WebApplication1.dll!WebApplication1.WebForm1.Page_Load(object sender, System.EventArgs e) Line 16   C#
System.Web.dll!System.Web.UI.Control.LoadRecursive() + 0x74 bytes   
System.Web.dll!System.Web.UI.Page.ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint) + 0xb5e bytes   
System.Web.dll!System.Web.UI.Page.ProcessRequest(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint) + 0xb9 bytes    
System.Web.dll!System.Web.UI.Page.ProcessRequest() + 0x77 bytes 
System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously) + 0xa5 bytes 
System.Web.dll!System.Web.Util.AspCompatApplicationStep.ExecuteAspCompatCode() + 0x83 bytes 
System.Web.dll!System.Web.Util.AspCompatApplicationStep.OnAspCompatExecution() + 0x79 bytes

AspCompatApplicationStep.OnAspCompatExecution 코드를 보면 Server.CreateObject로 생성한 객체에 대한 별도의 배려를 확인할 수 있습니다.

private void OnAspCompatExecution()
{
    try
    {
        // ...[생략]...
        this.ExecuteAspCompatCode();
        // ...[생략]...
    }
    finally
    {
        // ...[생략]...
        foreach (object obj2 in this._staComponents)
        {
            if (!this.IsStaComponentInSessionState(obj2))
            {
                Marshal.ReleaseComObject(obj2);
            }
        }
        // ...[생략]...
    }
}

즉, Server.CreateObject는 STA COM 개체를 생성하면 _staComponents 컬렉션에 보관해 두고 Page 개체의 실행을 마친 후 Marshal.ReleaseComObject를 자동으로 호출해 줍니다.

이를 다른 말로 표현하면, Page 개체의 라이프 사이클이 완료되고 나서야 ReleaseComObject가 실행되므로 그 때까지는 COM 개체가 살아 있게 됩니다. 따라서 개발자가 직접 ReleaseComObject를 해주는 것보다 일반적으로 더 오랜 수명을 갖습니다.

물론, Server.CreateObject로 생성한 개체도 사용이 끝나자마자 개발자가 직접 ReleaseComObject를 호출해 명시적으로 해제할 수 있습니다. 그래도 OnAspCompatExecution에서는 다시 한번 ReleaseComObject를 호출하겠지만 영향은 없습니다.




정리해 보면, ASP.NET에서 COM 개체를 사용하는 방법은 다음과 같이 2가지가 있습니다.

=== 방법 1: Server.CreateObject 사용 ===
WebTestHelperLib.IComAptTest catc = Server.CreateObjectFromClsid("{48D11CC5-C50A-403D-A4AC-0825A56E5C13}") 
            as WebTestHelperLib.IComAptTest;

=== 방법 2: 직접 생성/해제 ===
WebTestHelperLib.ComAptTestClass catc = new WebTestHelperLib.ComAptTestClass();

// 또는

Type type = Type.GetTypeFromCLSID(new Guid("{48D11CC5-C50A-403D-A4AC-0825A56E5C13}"));
WebTestHelperLib.IComAptTest catc = Activator.CreateInstance(type) as WebTestHelperLib.IComAptTest;

// 이후 반드시 COM 참조 횟수를 개발자가 직접 해제
Marshal.ReleaseComObject(catc);

개발자들이 실수를 절대 하지 않는다는 보장만 있다면 "방법 2"가 나을 수 있겠지만... 역시 그건 무리겠죠. ^^ 차라리 안전하게 방법 1로 하고 명시적인 해제 코드를 넣도록 하는 것이 더 낫습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 




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/20232194닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232190닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232201오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232395닷넷: 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  ...