使用Ninject 2.0和ASP .Net 3.5

GK.*_*GK. 3 c# dependency-injection ninject inversion-of-control

我正在尝试将Ninject 2.0与Asp .Net 3.5 Web应用程序一起使用.以下是我正在使用的DLLS及其版本.

  • Ninject.dll - v2.0.0.0
  • Ninject.Extensions.Logging.dll v2.0.0.0
  • Ninject.Web.dll v1.0.0.0

在我的global.ascx.cs中,我有以下方法.

protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel();            
        kernel.Bind<IDataAccess>().To<DataAccessEntBlock>().InSingletonScope();
        return kernel;
    }
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,我得到以下错误.

Error activating ILoggerFactory
No matching bindings are available, and the type is not self-bindable.
Activation path:
 1) Request for ILoggerFactory

Suggestions:
 1) Ensure that you have defined a binding for ILoggerFactory.
 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
 3) Ensure you have not accidentally created more than one kernel.
 4) If you are using automatic module loading, ensure the search path and filters are
Run Code Online (Sandbox Code Playgroud)

正确.

即使我没有尝试注册Logger,我也不理解,似乎它正试图创建它自己的.我该如何解决这个错误?我是否必须使用任何Ninject的扩展记录器?

谢谢GK

Pet*_*yer 6

错误表明在某处,Ninject正在尝试将ILoggerFactory接口解析为具体类.根据您上面提到的参考资料,听起来您是ASP.Net网络应用程序是基于WebForms而不是ASP.Net MVC应用程序.

考虑到这一点,您的页面应该派生自PageBaseNinject Web库提供的抽象类.该类具有以下属性定义:

[Inject]
public ILogger Logger { get; set; }
Run Code Online (Sandbox Code Playgroud)

因此,当您的页面被实例化时,Ninject会尝试将记录器注入页面上的属性.正如错误所暗示的那样,您需要ILoggerFactory为以及为此定义绑定ILogger; 但是,你提供的唯一绑定是IDataAccess.您还需要加载日志记录扩展库中定义的其中一个模块.我相信你可以选择NLog和Log4Net.因此,例如,如果您想使用Log4Net,您的CreateKernel功能将如下所示:

protected override IKernel CreateKernel()
{
    IKernel kernel = new StandardKernel(new Log4netModule());            
    kernel.Bind<IDataAccess>().To<DataAccessEntBlock>().InSingletonScope();
    return kernel;
}
Run Code Online (Sandbox Code Playgroud)

这假设您using Ninject.Extensions.Logging.Log4net;在文件中有一个语句.

在任何一种情况下,您都必须选择一个记录器并加载它的绑定(通过模块),因为Ninject Web库需要它.如果您现在没有任何日志记录问题,您可以选择提供实现ILoggerFactory并且ILogger不执行任何操作(即"null"记录器)并自行绑定您的虚拟ILoggerFactory.