문제

COM Interop에 등록 된 DLL의 .NET 코드 내에서 Entlib 3.1을 사용하려고합니다. 구성 파일은 어디에 넣습니까?

또는 DLL 코드 내에서 Entlib 구성을 가져와야하는 위치를 지정하는 방법이 있습니까? 내 DLL이 COM에서 호출되므로 Exe가 무엇을 부를 지 항상 모릅니다.

나는 'CallingApp'과 'mycomthing'이라는 두 가지 클래스와 함께 Entlib 로깅을 사용하는 간단한 앱을 만들었습니다. CallingApp에서 mycomthing 메소드를 호출하면 CallingApp의 구성 파일에서 구성을 사용하여 로그를 작성합니다. VBS 스크립트에서 mycomthing 방법을 호출 할 때 COM을 통해 "로깅을위한 구성 섹션은 구성 소스에서 찾을 수 없습니다"오류가 발생합니다. my comthing.dll.config 파일은 bin debug 폴더의 등록 된 comthing.dll과 동일한 폴더에 있습니다.

감사해요!

도움이 되었습니까?

해결책

대답은 기본적으로 Enterprise Library가 EXE의 구성 파일을 사용한다는 것입니다. COM을 포함하여 DLL을 생산하는 경우 정당한 이유가 있으시면 통화 실행 파일에 의존하고 싶지 않을 수 있습니다. 이에 대한 한 가지 해결책 (다른 사람들이있을 수 있음)은 기본 객체를 사용하는 대신 직접 엔터프라이즈 라이브러리 객체를 만들고 구성을 얻을 수있는 위치를 알려주는 것입니다. 이것은 보이는 것만 큼 무섭지 않으며 Entlib 또는 그와 비슷한 것을 다시 컴파일 할 필요가 없습니다.

단순히 logger.write ()를 사용하는 대신 다음을 수행했습니다. a) dll의 구성 파일을 사용하여 로그 라이터를 만듭니다.

        string dllConfigFilename = Assembly.GetExecutingAssembly().Location + ".config";
        FileConfigurationSource exceptionsSource = new FileConfigurationSource(dllConfigFilename);
        LogWriterFactory writerFactory = new LogWriterFactory(exceptionsSource);
        logWriter = writerFactory.Create();

b) 그런 다음 코드 내 에서이 로그 라이터를 사용하십시오.

        LogEntry log = new LogEntry();
        log.Message = message;
        log.Categories = new string[] { "General" };
        logWriter.Write(log);

다음은 내가 만든 샘플 객체에 대한 전체 코드입니다. 참고 문헌은 Microsoft.practices.enterpriselibrary.common, Microsoft.practices.enterpriselibrary.logging, microsoft.practices.objectbuilder, system, system.data, system.windows.forms, system.xml :입니다.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace COMThing
{
    [ComVisible(true)]
    public class MyComThing : MyComInterface
    {
        LogWriter logWriter; 

        public MyComThing()
        {
            string dllConfigFilename = Assembly.GetExecutingAssembly().Location + ".config";
            FileConfigurationSource exceptionsSource = new FileConfigurationSource(dllConfigFilename);
            LogWriterFactory writerFactory = new LogWriterFactory(exceptionsSource);
            logWriter = writerFactory.Create();
        }

        public bool ProcessMessage(string message)
        {
            LogEntry log = new LogEntry();
            log.Message = message;
            log.Categories = new string[] { "General" };
            logWriter.Write(log);
            MessageBox.Show(message);
            return true;
        }
    }

}

이 프로젝트에는 comthing.dll.config 파일이 포함되어 'output directory to'always '를 설정했습니다. 이것은 응용 프로그램 이벤트 로그에 로그 정보를 작성하는 사소한 구성입니다. 구성 파일의 내용은 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add source="COMThing Logger" formatter="Text Formatter" log="Application"
        machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        name="Formatted EventLog TraceListener" />
    </listeners>
    <formatters>
      <add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Formatted EventLog TraceListener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events">
        <listeners>
          <add name="Formatted EventLog TraceListener" />
        </listeners>
      </allEvents>
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="Formatted EventLog TraceListener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
</configuration>

빌드 체크의 프로젝트 속성에서 'com interop에 대한 등록'. 프로젝트를 빌드 한 다음 다음 .VBS 파일을 만듭니다.

Set obj = CreateObject("COMThing.MyComThing")
obj.ProcessMessage("called from com by vbs")

이 vbs 파일을 두 번 클릭하면 'com에서 vbs에서 호출 된 텍스트'가있는 메시지 상자가 표시되고 응용 프로그램 이벤트 로그에 항목을 작성해야합니다. 이는 실행 프로세스가 C : Windows System332 Wscript.exe (또는 이와 유사한)이지만 DLL의 구성 파일에서 구성이 발생하고 있음을 보여줍니다.

나는 이것을 정보를 기반으로합니다 여기 '여러 configurationSources 사용'아래

로거 클래스에는 인수가 다른 많은 멋진 도우미 방법이 포함되어 있습니다. 우리는 로그 라이터 클래스를 사용하고 있기 때문에 우리는이 마술을 얻지 못합니다. 개인적으로 Logger를 기반으로 같은 작업을 수행하기 위해 내 도서관 내에 다른 수업을 만들 것입니다.

참조 기사는 데이터베이스 및 예외 애플리케이션 블록에 적용되는 동일한 원리를 보여줍니다. 아마도 동일한 모델은 대부분/모두에 적용될 수 있습니다.

다른 팁

내가 직면 한 관련 문제를 확인하십시오. 어쩌면 도움이 될 수도 있습니다.

게시 된 .NET 사이트에 COM 구성 요소를 포함시키는 방법은 무엇입니까?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top