【问题标题】:Unity: The type LogWriter cannot be constructedunity:无法构造类型LogWriter
【发布时间】:2012-10-18 08:44:44
【问题描述】:

对于以下“项目”,我在解决 Unity for DI 时遇到了一个非常烦人且莫名其妙的错误。

InvalidOperationException - 无法构造类型 LogWriter。 您必须配置容器以提供此值。

?ex.Message; “依赖关系解析失败,类型= \"WindowsFormsApplication1.Performance\",名称 = \"(none)\"。\r\n异常发生 while: 解析时。\r\n异常 是:InvalidOperationException - LogWriter 类型不能是 建。你必须配置容器来提供这个 值。\r\n-------------------------------------------- ---\r\n在 异常发生的时间,容器是:\r\n\r\n Resolving WindowsFormsApplication1.Performance,(none)\r\n 解析参数 构造函数的“lw” WindowsFormsApplication1.Performance(Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter lw, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionManager em)\r\n 正在解决 Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter,(none)\r\n"

?ex.StackTrace; “ 在 Microsoft.Practices.Unity.UnityContainer.DoBuildUp(类型 t,对象 现有,字符串名称,IEnumerable1 resolverOverrides) in e:\\Builds\\Unity\\UnityTemp\\Compile\\Unity\\Unity\\Src\\UnityContainer.cs:line 515\r\n at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable1 resolverOverrides) 在 e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:line 485\r\n 在 Microsoft.Practices.Unity.UnityContainer.Resolve(类型 t, 字符串名称,ResolverOverride[] resolverOverrides) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:line 173\r\n 在 Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer 容器,ResolverOverride[] 覆盖)在 e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainerExtensions.cs:line 504\r\n 在 WindowsFormsApplication1.Form1.OnLoad(EventArgs e) 中 D:\Devzone\Tasking\WindowsFormsApplication1\Form1.cs:line 33"

形式:

  protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                IUnityContainer container = new UnityContainer();
                Performance p = container.Resolve<Performance>();
            }
            catch (Exception ex)
            {

            }
        }

依赖类:

 public class Performance
    {
        public Performance(LogWriter lw, ExceptionManager em)
        {
        }
    }

配置文件:

<?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" />
        <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
        <listeners>
            <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                source="Enterprise Library Logging" formatter="Text Formatter"
                log="" machineName="." traceOutputOptions="None" />
        </listeners>
        <formatters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
                name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="General">
                <listeners>
                    <add name="Event Log Listener" />
                </listeners>
            </add>
            <add switchValue="All" name="Category2" />
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events" />
            <notProcessed switchValue="All" name="Unprocessed Category" />
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
                <listeners>
                    <add name="Event Log Listener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
    <exceptionHandling>
        <exceptionPolicies>
            <add name="Policy">
                <exceptionTypes>
                    <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                        postHandlingAction="NotifyRethrow" />
                </exceptionTypes>
            </add>
        </exceptionPolicies>
    </exceptionHandling>
</configuration>

【问题讨论】:

    标签: c# unity-container


    【解决方案1】:

    您需要将企业库扩展添加到您的容器中。没有它,容器就不会读取配置文件,因此不知道如何创建 Entlib 对象,例如 LogWriter。

    【讨论】:

    • 对于其他人来说,这就是我需要做的一切: var container = new UnityContainer().AddNewExtension();
    • 我花了一些时间才弄清楚,但这个答案非常有帮助。如果有人想在 unity.config 文件中声明它,应该这样做:
    • EnterpriseLibraryCoreExtension 已从 Enterprise Library 6 中删除。您可以调用工厂构造函数并传递 ConfigurationSourceFactory。迁移指南中的详细信息:entlib.codeplex.com/downloads/get/668962
    • @UriahBlatherwick 谢谢!您的评论值得作为答案发布!
    【解决方案2】:

    Activation error occured while trying to get instance of type LogWriter, key ""

    检查您的配置文件,它必须具有正确的默认“loggingConfiguration”部分

    【讨论】:

      【解决方案3】:

      为了让 Unity 构造你的 Performance 类,它需要知道如何构造 ILogWriter 的实现。

      我在你的代码中看不到你告诉 Unity 为 ILogWriter 接口创建什么类的任何地方,所以我怀疑你可能需要添加这个。

      【讨论】:

      • 他使用的不是ILogWriter,而是LogWriter,这是一个具体的类,但是他没有在其构造函数中提供LogWriter需要的依赖。
      • 这是DI没错,所以我在Performance类的构造函数中要求一个LogWriter(ILogWriter的具体实现)?
      • 是的,你确实是,我一定是这么想的。那么 LogWriter 有无参数的构造函数吗?
      • 克里斯不在。我相信有很多方法可以做到这一点,但他是我记得的简单方法。 Unity“只知道”它的 Ent Libs 构造函数,如果你给它一个 EntLib 扩展,我猜这是某种映射?
      【解决方案4】:

      试试这个:

      protected override void OnLoad(EventArgs e)
              {
                  base.OnLoad(e);
      
                  try
                  {
                      IUnityContainer container = new UnityContainer();
                      container.RegisterType<ILogWriter, LogWriter>();
                      container.RegisterType<ExceptionManager>();
                      container.RegisterType<Performance>(new InjectionConstructor(typeof(ILogWriter), typeof(ExceptionManager));                    
                      Performance p = container.Resolve<Performance>();
                  }
                  catch (Exception ex)
                  {
      
                  }
              }
      

      【讨论】:

        【解决方案5】:

        LogWriter 没有空构造函数或具有所有具体类型参数的构造函数:LogWriter Constructor

        所以 Unity 未能构建它,正如它所说,它需要您的帮助,通过配置容器来提供实现。

        作为确认,ExceptionManager 可能会被解决,因为它只有一个constructor,也是无参数的:)

        【讨论】:

        • 嗯,你说的很有道理,但我不记得自己曾经关心过 Ent Lib 块中类型的构造函数。
        猜你喜欢
        • 1970-01-01
        • 2013-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多