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

Entity Framework 4.1 - CodeFirst 개체의 직렬화 시 순환 참조 해결하는 방법 - 두 번째 이야기

지난번 이야기에서 언급했던,

Entity Framework 4.1 - CodeFirst 개체의 직렬화 시 순환 참조 해결하는 방법
; https://www.sysnet.pe.kr/2/0/1086

순환 참조를 해결하는 두 번째 방법을 살펴볼 텐데요. 혹시 이에 대한 힌트가 지난번 오류 메시지에서 약간 포함되어 있었다는 것을 눈치채신 분이 계실까요? ^^

System.Runtime.Serialization.SerializationException: Object graph for type 'System.Collections.Generic.HashSet`1[[SubEntity, App_Code.xdcj8jsd, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]' contains cycles and cannot be serialized if reference tracking is disabled.


결국 "reference tracking" 옵션을 활성화시키면 된다는 이야기인데요. 즉, WCF 서비스의 출력으로 사용되는 DataContractSerializer에 "reference tracking" 옵션을 켜두고 그것을 지정해 주면 되는 것입니다.

이와 관련해서 검색해 보면, 다행히 그 방법이 설명된 글들이 나옵니다.

Preserving Object Reference in WCF
; http://blogs.msdn.com/b/sowmy/archive/2006/03/26/561188.aspx

Specifying Data Transfer in Service Contracts
; https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/specifying-data-transfer-in-service-contracts

순서를 나열해 보면 다음과 같습니다.

  1. svc의 Factory 재정의
  2. ServiceHostFactory에 사용자 정의 ServiceHost 설정
  3. ServiceHost의 OnOpening 메서드를 재정의해서 사용자 정의 DataContractSerializerOperationBehavior 설정
  4. DataContractSerializerOperationBehavior의 CreateSerializer 메서드를 재정의해서 "reference tracking"이 가능한 DataContractSerializer 설정

뭐... 약간은 복잡하긴 하지만, 그래도 할만한 수준입니다. ^^ 지난번 글에서 문제가 되었던 소스 코드로부터 위의 순서를 그대로 적용해 보겠습니다.

우선 Service.svc 파일을 열어서 다음과 같이 ServiceFactory를 지정합니다. (주의: Web Site 모델의 경우, 네임스페이스가 생략되므로 아래와 같이 클래스 명만 지정하면 되지만, Web Application Project의 경우에는 필히 네임스페이스를 같이 지정해 주어야 합니다.)

<% @ServiceHost Language=C# Debug="true" Service="MyService" 
Factory="CustomServiceFactory" CodeBehind="~/App_Code/Service.cs" %>

Factory를 지정했으니, 그 이름에 맞게 클래스 파일을 하나 생성하고 다음과 같이 CreateServiceHost 메서드를 재정의합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Activation;

public class CustomServiceFactory : ServiceHostFactory
{
    protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        return new CustomServiceHost(serviceType, baseAddresses);
    }
}

이어서, CustomServiceHost 클래스 파일을 생성하고 OnOpeneing 메서드를 재정의 해줍니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;

public class CustomServiceHost : ServiceHost
{
    public CustomServiceHost(object singletonInstance, params Uri[] baseAddresses) : base(singletonInstance, baseAddresses) { }

    public CustomServiceHost(Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses) { }

    protected override void OnOpened()
    {
        base.OnOpened();
    }

    protected override void OnOpening()
    {
        base.OnOpening();
        AddBehavior();
    }
}

AddBehavior에서는 개별 WCF 메서드에 새로운 DataContractSerializerOperationBehavior를 설정해 주면 되는데요. 이에 대해서는 위에서 제가 소개한 "Preserving Object Reference in WCF" 글에 포함된 소스 코드에 따라 다음과 같이 구현해 줄 수 있습니다. (사실, 이 코드에는 문제가 있지만 나중에 지적하겠습니다.)

void AddBehavior()
{
    if (base.Description != null)
    {
        foreach (ServiceEndpoint ep in this.Description.Endpoints)
        {
            foreach (OperationDescription op in ep.Contract.Operations)
            {
                op.Behaviors.Add(new ReferencePreservingDataContractSerializerOperationBehavior(op));
            }
        }
    }
}

거의 다 왔군요. 마지막으로 ReferencePreservingDataContractSerializerOperationBehavior 클래스 파일을 만들고 아래와 같이 CreateSerializer 메서드를 재정의해주면 됩니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.Xml;

public class ReferencePreservingDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior
{
    public ReferencePreservingDataContractSerializerOperationBehavior(OperationDescription operationDescription)
        : base(operationDescription)
    {
    }

    public override XmlObjectSerializer CreateSerializer(
      Type type, string name, string ns, IList<Type> knownTypes)
    {
        return CreateDataContractSerializer(type, name, ns, knownTypes);
    }

    private static XmlObjectSerializer CreateDataContractSerializer(
      Type type, string name, string ns, IList<Type> knownTypes)
    {
        return CreateDataContractSerializer(type, name, ns, knownTypes);
    }

    public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
    {
        return new DataContractSerializer(type, name, ns, knownTypes,
            0x7FFF /*maxItemsInObjectGraph*/,
            false/*ignoreExtensionDataObject*/,
            true/*preserveObjectReferences*/,
            null/*dataContractSurrogate*/);
    }
}

이걸로 일단 구현은 끝입니다. 빌드하고 실행해 보면, 결과는 어떨까요? ^^

아쉽게도 여전히 오류가 발생합니다. 문제를 추적해 보면, AddBehavior 메서드의 Description.Endpoints 루프가 실행되지 않는 것을 확인할 수 있습니다.

void AddBehavior()
{
    if (base.Description != null)
    {
        foreach (ServiceEndpoint ep in this.Description.Endpoints)
        {
            System.Diagnostics.Debug.WriteLine("실행되지 않음!!!");

            foreach (OperationDescription op in ep.Contract.Operations)
            {
                op.Behaviors.Add(new ReferencePreservingDataContractSerializerOperationBehavior(op));
            }
        }
    }
}

왜냐하면, 이렇게 .svc 파일의 ServiceFactory를 재정의해서 Endpoints를 열람하려면 web.config에서 명시적으로 endpoint 노드를 지정해 주어야만 열람이 되기 때문입니다.

<system.serviceModel>
    <services>
        <service name="MyService">
            <endpoint contract="IMyService" binding="basicHttpBinding"/>
        </service>
    </services>
    
    <behaviors>
        <serviceBehaviors>
            <behavior name="">
                <serviceDebug includeExceptionDetailInFaults="true"/>
                <serviceMetadata httpGetEnabled="true"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

다시 테스트를 해볼까요? 하지만, 그래도 오류가 발생할 것입니다. 다행히 오류 메시지를 살펴보면 문제의 원인을 쉽게 파악할 수 있습니다.

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: ReferencePreservingDataContractSerializerOperationBehavior
 contract: http://tempuri.org/:IMyService ----> System.ArgumentException: Calling IWsdlExportExtension.ExportContract twice with the same ContractDescription is not supported.
   at System.ServiceModel.Description.MessageContractExporter.CreateMessage(MessageDescription message, Int32 messageIndex, Message& wsdlMessage)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   --- End of inner ExceptionDetail stack trace ---

말 그대로, DataContractSerializerOperationBehavior가 2개 이상 설정되었다는 것! 왜냐하면 기본적으로 모든 WCF 메서드에 DataContractSerializerOperationBehavior가 존재하기 때문인데, 이로 인해 사실상 AddBehavior 코드가 다음과 같이 변경되어야만 합니다.

void AddBehavior()
{
    if (base.Description != null)
    {
        foreach (ServiceEndpoint ep in this.Description.Endpoints)
        {
            foreach (OperationDescription op in ep.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior =
                    op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;

                if (dataContractBehavior != null)
                {
                    op.Behaviors.Remove(dataContractBehavior);
                }

                op.Behaviors.Add(new ReferencePreservingDataContractSerializerOperationBehavior(op));
            }
        }
    }
}

이제 정말 끝난 걸까요? ^^ 넵. 이것으로 모든 오류 수정이 끝났고, 이제 GetMyEntities WCF 메서드를 호출해도 정상적으로 동작을 합니다.

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/26/2021]

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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13248정성태2/7/20234335오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20235236VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234431개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20235017.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234418VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20235248디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234696디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20234088디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234261디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233942디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20236094.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235787.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235236개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234910개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20236009개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237364오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20235016스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20234046오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234437개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235464.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235591.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20235217개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234901.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20234101개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234558Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234703오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...