【问题标题】:Adding dependency injection to Nlog using Ninject使用 Ninject 向 Nlog 添加依赖注入
【发布时间】:2012-04-24 16:43:31
【问题描述】:

我正在尝试使用Ninject 将依赖注入添加到Nlog 以进行单元测试,但我无法让它工作。 :( 调用 GetCurrentClassLogger() 时出现 NullReferenceException。 我是 Nlog 和 Ninject 的新手,这实际上是我第一次使用它们。

主要

using NLog;
using Ninject;
using Ninject.Extensions.Logging;
using Ninject.Extensions.Logging.NLog2;
public class Program
{
    static void Main(string[] args)
    {
        var kernel = new StandardKernel(new NLogModule());
        var logFactory = kernel.Get<ILoggerFactory>();
        var run = new MyClass(logFactory);
    }
}

我的班级

using Ninject.Extensions.Logging;
public class MyClass
{
    private readonly ILogger _log;

    public MyClass(ILoggerFactory logFactory)
    {
        _log = logFactory.GetCurrentClassLogger();
    }

    public void DoWork()
    {
        _log.Info("Doing work!");
    }
}

希望有人可以帮助我。

【问题讨论】:

    标签: c# dependency-injection ninject nlog ninject-extensions


    【解决方案1】:

    这就是我最终解决它的方法。感谢 Claus Jørgensen 在 IRC 上帮助我:)

    显然在使用 NLog 扩展时有一些自动绑定,所以 new StandardKernel(new NLogModule()); 会导致模块被加载两次。

    主要

    using Ninject;
    public class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            var run = kernel.Get<MyClass>();
            run.DoWork();
        }
    }
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多