1

我试图伪造企业库LogWriter,因此在我运行单元测试时它不会执行任何日志记录,所以它在简化版本中看起来像这样:

public class MockLogger : ILogger
{
      public MockLogger()
      {
      }

      public void Write(object message)
      {        
      }

      public void Write(object message, string category)
      {     
      }

      public void Write(object message, string category, int eventId)
      { 
      }

      public void Write(object message, string category, int eventId, int priority)
      {
      }

      public void Write(object message, string category, int eventId, int priority,   TraceEventType severity)
      {
      }
}

public class Logger : ILogger
{
      LogWriter writer;
      public Logger()
      {
          writer = (new LogWriterFactory()).Create();

      }

      public Logger(LogWriter logWriter)
      {
          writer = logWriter;
      }

      public void Write(LogEntry logEntry)
      {
          writer.Write(logEntry);
      }

      public void Write(object message)
      {
          writer.Write(message);
      }

      public void Write(object message, string category)
      {
          writer.Write(message, category);
      }

      public void Write(object message, string category, int eventId)
      {
          writer.Write(message, category, eventId);
      }

      public void Write(object message, string category, int eventId, int priority)
      {
          writer.Write(message, category, eventId, priority);
      }

      public void Write(object message, string category, int eventId, int priority,   TraceEventType severity)
      {
          writer.Write(message, category, priority, eventId, severity);
      }

      public bool ShouldLog(LogEntry logEntry)
      {
          return writer.ShouldLog(logEntry);
      }
}

然后我试图通过配置解决它:

<unity xmlns="http://schemas.microsoft.com/practices/2012/unity">
<alias alias="ILogger" type="ConsoleApplicationTest.ILogger, ConsoleApplicationTest" />
<namespace name="ConsoleApplicationTest" />
<assembly name="ConsoleApplicationTest" />
<container>
  <register type="ConsoleApplicationTest.ILogger, ConsoleApplicationTest" name="logger" mapTo="ConsoleApplicationTest.Logger, ConsoleApplicationTest">
  </register>
</container>
<container name="Mock">
  <register type="ConsoleApplicationTest.ILogger, ConsoleApplicationTest" name="mockLogger" mapTo="ConsoleApplicationTest.MockLogger, ConsoleApplicationTest">
  </register>
</container>

var container = new UnityContainer();
container.LoadConfiguration();
var logger = container.Resolve<ILogger>();

我得到的错误如下:

依赖项解析失败,type = "ConsoleApplicationTest.ILogger",name = "(none)"。异常发生时:解决时。例外是: InvalidOperationException - ILogger 类型没有可访问的构造函数。

这两个类都有一个无参数的构造函数。我应该怎么做才能解决这个错误?使用 .NET 4.5

4

1 回答 1

3

因为您已经使用 注册了您的类型name="logger"并且name="mockLogger"您已经创建了命名注册,所以您需要在调用 Resolve 时传入名称:

var container = new UnityContainer();
container.LoadConfiguration();
var logger = container.Resolve<ILogger>("logger"); // or "mockLogger"
于 2013-07-26T20:24:56.933 回答