尝试获取LogWriter类型的实例时出现激活错误,键“”?

时间:2011-10-18 21:23:35

标签: c# asp.net vb.net enterprise-library

我有asp.net网站。我在网站上添加了Microsoft.Practices.EnterpriseLibrary.Logging.dll的引用。

在web.cofig文件中,我定义如下。

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
        fileName="C:\Temp\RollingFlatFile.log" footer="----------------------------------------"
        formatter="Text Formatter" header="----------------------------------------"
        rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="20"
        timeStampPattern="yyyy-MM-dd" maxArchivedFiles="3" traceOutputOptions="None"
        filter="All" />
      </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
        template="Timestamp: {timestamp(local)}{tab}Message: {message}{tab}Category: {category}{tab}Priority: {priority}{tab}EventId: {eventid}{tab}ActivityId: {property(ActivityId)}{tab}Severity: {severity}{tab}Title:{title}{tab}"
        name="Brief Format Text" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
        template="Timestamp: {timestamp}{tab}Message: {message}{tab}Category: {category}{tab}Priority: {priority}{tab}EventId: {eventid}{tab}Severity: {severity}{tab}Title: {title}{tab}Activity ID: {property(ActivityId)}{tab}Machine: {localMachine}{tab}App Domain: {localAppDomain}{tab}ProcessId: {localProcessId}{tab}Process Name: {localProcessName}{tab}Thread Name: {threadName}{tab}Win32 ThreadId:{win32ThreadId}{tab}Extended Properties: {dictionary({key} - {value}{tab})}"
        name="Text Formatter" />
    </formatters>
    <logFilters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
        minimumPriority="2" maximumPriority="99" name="Priority Filter" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
        enabled="true" name="LogEnabled Filter" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
        categoryFilterMode="AllowAllExceptDenied" name="Category Filter">
        <categoryFilters>
          <add name="BlockedByFilter" />
        </categoryFilters>
      </add>
    </logFilters>
    <categorySources>
      <add switchValue="All" name="Important">
        <listeners>
          <add name="Formatted EventLog TraceListener" />
          <add name="Rolling Flat File Trace Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category">
        <listeners>
          <add name="UnprocessedFlatFile" />
        </listeners>
      </notProcessed>
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="Formatted EventLog TraceListener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
</configuration>

当我在下面运行代码异常时。

defaultWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
//Activation error occured while trying to get instance of type LogWriter, key ""

如何解决这个问题?

3 个答案:

答案 0 :(得分:12)

您的完整配置引用了未定义的跟踪侦听器。这导致Enterprise Library运行时在尝试解析这些引用时抛出运行时异常。

我注释掉了未使用的侦听器(并将默认类别更改为Important)并且它正在运行:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
      defaultCategory="Important" logWarningsWhenNoCategoriesMatch="true">
        <listeners>
            <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
              listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
              fileName="C:\Temp\RollingFlatFile.log" footer="----------------------------------------"
              formatter="Text Formatter" header="----------------------------------------"
              rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="20"
              timeStampPattern="yyyy-MM-dd" maxArchivedFiles="3" traceOutputOptions="None"
              filter="All" />
        </listeners>
        <formatters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
              template="Timestamp: {timestamp(local)}{tab}Message: {message}{tab}Category: {category}{tab}Priority: {priority}{tab}EventId: {eventid}{tab}ActivityId: {property(ActivityId)}{tab}Severity: {severity}{tab}Title:{title}{tab}"
              name="Brief Format Text" />
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
              template="Timestamp: {timestamp}{tab}Message: {message}{tab}Category: {category}{tab}Priority: {priority}{tab}EventId: {eventid}{tab}Severity: {severity}{tab}Title: {title}{tab}Activity ID: {property(ActivityId)}{tab}Machine: {localMachine}{tab}App Domain: {localAppDomain}{tab}ProcessId: {localProcessId}{tab}Process Name: {localProcessName}{tab}Thread Name: {threadName}{tab}Win32 ThreadId:{win32ThreadId}{tab}Extended Properties: {dictionary({key} - {value}{tab})}"
              name="Text Formatter" />
        </formatters>
        <logFilters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
              minimumPriority="2" maximumPriority="99" name="Priority Filter" />
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
              enabled="true" name="LogEnabled Filter" />
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
              categoryFilterMode="AllowAllExceptDenied" name="Category Filter">
                <categoryFilters>
                    <add name="BlockedByFilter" />
                </categoryFilters>
            </add>
        </logFilters>
        <categorySources>
            <add switchValue="All" name="Important">
                <listeners>
                    <!--<add name="Formatted EventLog TraceListener" />-->
                    <add name="Rolling Flat File Trace Listener" />
                </listeners>
            </add>
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events" />
            <notProcessed switchValue="All" name="Unprocessed Category">
                <listeners>
                    <!--<add name="UnprocessedFlatFile" />-->
                </listeners>
            </notProcessed>
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
                <listeners>
                    <!--<add name="Formatted EventLog TraceListener" />-->
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
</configuration>

线索是内在的例外。在InnerException.Message结束时,它说:

  

解析System.Diagnostics.TraceListener,Formatted EventLog   的TraceListener

以上配置在app.config中。然后Program.cs包含:

class Program
{
    static void Main(string[] args)
    {
        LogWriter logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
        logWriter.Write("Test");
     }
}

答案 1 :(得分:8)

编辑:在EL 6.0下,不再有Unity依赖 在上次编辑时(2013年8月),Unity 3是当前的产品。 Unit 3.0

以下有关EL的App.config编辑器的一些提示仍然有用。 还会显示el5到el6的一些代码更改。

这是我试图澄清的。 el5.0错误 错误示例

  

依赖项的解析失败,type =   “Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter”,name =   “(没有)”。在解决时发生异常:例外情况是:   InvalidOperationException无法构造LogWriter类型。   您必须配置容器以提供此值。

执行摘要: Unity无法看到库或团队无法找到app.config条目,应用程序配置条目对于正在使用的库不完整,或者存在一些定位问题。 注意所有这些要点。

Enterprise Library 6 download site 下载vsix文件

Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix

您可以使用它来正确编辑app.config。

仍然使用nuget来安装软件包,但是你需要上面的下载才能正确编辑app.config

PM > Install-Package EnterpriseLibrary.Logging
PM> Install-Package EnterpriseLibrary.Common
Pm> Install-Package Unity         
PM> Install-Package EnterpriseLibrary.ExceptionHandling

您可能感兴趣的还有一些耳鼻喉科图书馆。 http://nuget.org/packages?q=entlib

using System;  
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.Unity;
using Microsoft.Practices.Unity;  // << SEPARATE since EL6 , unity 3 has own install.

public class abc
{
    /// <summary>
    /// Unity Container with key dependencies registered
    /// </summary>
    public static UnityContainer UC { get; private set; }

    private static IUnityContainer _IUContainer;// not sure if this is needed

    public static LogWriter LogWtr;
    public static ExceptionManager ExcMgr;

    /// <summary>
    /// Controller Bootstrap to manage as singleton via static properties and therefore ONLY 1 Unity Container
    /// </summary>
    static bootstrap()
    {
        UC = new UnityContainer(); // one container per work process. managing and resolving dependencies

        //  DO NO DO THIS WITH NEW VERSION OF Enterprise LIBRARY this was v5, v6 does not need this
        // now we tell unity about the container manager inside EntLib.
        // we dont want 2 containers, so we tell UNity look after EntLib as well please
        //  UC.AddNewExtension<EnterpriseLibraryCoreExtension>();

        //No need to add The extensions individually.
        //no longer required and indeed Library documents this as obselete
        //    UC.AddNewExtension<LoggingBlockExtension>();** 
        //================ END OF OLD V5 approach  ========================

        LogWtr = UC.Resolve<LogWriter>();
        ExcMgr = UC.Resolve<ExceptionManager>();

        // other initializations here
    }
}

使用下载的配置控制台即VSIX。右键单击app.config。

EntLib Config Console

APP.CONFIG文件应该有一个包含正在使用的ENtLibraries的部分。 您需要确保正在运行的项目的app.config web配置 使用企业库控制台配置日志记录或异常处理时,将添加这些条目。

 <configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />

答案 2 :(得分:1)

这对我有用, EL 6.0,不使用Unity

来自web.config文件的Init Logger,在Global.asax上 - &gt;的Application_Start

var configSource = ConfigurationSourceFactory.Create();
Logger.SetLogWriter(new LogWriterFactory(configSource).Create());

在MVC控制器上使用记录器

Logger.Write("Hello", "General");