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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12746정성태7/31/20219217개발 환경 구성: 588. 네트워크 장비 환경을 시뮬레이션하는 Packet Tracer 프로그램 소개
12745정성태7/31/20217053개발 환경 구성: 587. Azure Active Directory - tenant의 관리자 계정 로그인 방법
12744정성태7/30/20217672개발 환경 구성: 586. Azure Active Directory에 연결된 App 목록을 확인하는 방법?
12743정성태7/30/20218385.NET Framework: 1083. Azure Active Directory - 외부 Token Cache 저장소를 사용하는 방법파일 다운로드1
12742정성태7/30/20217584개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
12741정성태7/29/20218797.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법파일 다운로드1
12740정성태7/29/20217437오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/20217402오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/20218030오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/20216964오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/20217522오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20218066.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202124075스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202111346.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216630오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20217833개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/20219350개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/20218308.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/20217719.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/20218767.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/20218597VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/20217261오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/202110034개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/20217650오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/20217490오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/20218074오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...